使用jQuery获取选定复选框的值


83

我想遍历复选框组“ locationthemes”,并使用所有选定值构建一个字符串。所以,当复选框2和4被选出的结果将是:“3,8”

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>

我在这里检查过:http : //api.jquery.com/checked-selector/,但是没有示例如何通过其名称选择复选框组。

我怎样才能做到这一点?

Answers:


176

在jQuery中,只需使用诸如

$('input[name="locationthemes"]:checked');

选择名称为“ locationthemes”的所有选中输入

console.log($('input[name="locationthemes"]:checked').serialize());

//or

$('input[name="locationthemes"]:checked').each(function() {
   console.log(this.value);
});

演示版


VanillaJS中

[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
   console.log(cb.value); 
});

演示版


在ES6 /价差运算符中

[...document.querySelectorAll('input[name="locationthemes"]:checked')]
   .forEach((cb) => console.log(cb.value));

演示版


5
您,我的朋友,是救生员。
Haring10年

特别是我喜欢使用控制台日志的想法。感谢那。
所以S

32
$('input:checkbox[name=locationthemes]:checked').each(function() 
{
   // add $(this).val() to your array
});

工作演示

要么

使用jQuery的is()功能:

$('input:checkbox[name=locationthemes]').each(function() 
{    
    if($(this).is(':checked'))
      alert($(this).val());
});


18

映射阵列最快,最干净。

var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })

将以数组形式返回值:

array => [2,3]

假设检查了城堡和谷仓,而没有检查其他城堡和谷仓。


12

使用jQuery的map功能

var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
            checkboxValues.push($(this).val());
});

在此示例中,将checkboxName设置为“ locationthemes”的
前提是



2

因此,所有内容合而为一:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..有关选择器的注释[id*="checkbox"],它将获取其中包含字符串“ checkbox”的任何项目。这里有点笨拙,但是如果您尝试从.NET CheckBoxList之类的东西中拉出选定的值,那确实很好。在这种情况下,“复选框”将是您为CheckBoxList控件指定的名称。


1
@mike这很有用
Yii2Developer


1
var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

升级:var voyageIds = $('input[name="voyageId[]"]:checked:enabled').map(function() {return this.value; }).get();
威廉

1

来源-更多详细信息

使用jQuery获取选定的复选框值

然后,我们编写jQuery脚本以使用jQuery each()获得数组中选定的复选框值。使用此jQuery函数,它运行循环以获取检查的值并将其放入数组中。

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Get Selected Checkboxes Value Using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".btn").click(function() {
                var locationthemes = [];
                $.each($("input[name='locationthemes']:checked"), function() {
                    locationthemes.push($(this).val());
                });
                alert("My location themes colors are: " + locationthemes.join(", "));
            });
        });
    </script>
    </head>
    <body>
        <form method="POST">
        <h3>Select your location themes:</h3>
        <input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
        <label for="checkbox-1">Castle</label>
        <input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
        <label for="checkbox-2">Barn</label>
        <input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
        <label for="checkbox-3">Restaurant</label>
        <input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
        <label for="checkbox-4">Bar</label>
        <br>
        <button type="button" class="btn">Get Values</button>
    </form>
    </body>
    </html>

0

jQuery 3.3.1,单击按钮时获取所有选中复选框的值

$(document).ready(function(){
 $(".btn-submit").click(function(){
  $('.cbCheck:checkbox:checked').each(function(){
	alert($(this).val())
  });
 });			
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="vehicle1" name="vehicle1"  class="cbCheck" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2"  class="cbCheck" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3"  class="cbCheck" value="Boat">
  <label for="vehicle3"> I have a boat</label><br><br>
  <input type="submit" value="Submit" class="btn-submit">


0

现代化的方法:

const selectedValues = $('input[name="locationthemes"]:checked').map( function () { 
        return $(this).val(); 
    })
    .get()
    .join(', ');

我们首先找到具有给定名称的所有选定复选框,然后jQuery的map()遍历它们中的每个复选框,对其调用回调以获取值,然后将结果作为新的jQuery集合返回,该集合现在包含该复选框的值。然后,我们在其上调用get()以获取值的数组,然后使用join()将它们连接为单个字符串-然后将其分配给常量selectedValues。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.