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

109
我想循环遍历复选框组“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/,但是没有示例说明如何按名称选择复选框组。

我该怎么做?

12个回答

230

在 jQuery 中只需要使用属性选择器,如:

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

选择所有名为"locationthemes"且已勾选的输入框

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

//or

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

演示


使用原生JavaScript。

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

演示


在ES6/spread操作符中

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

演示


42
$('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());
});


26

映射数组是最快和最清晰的方法。

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

将返回像数组一样的值:

array => [2,3]

假设城堡和谷仓已经检查过了,其他地方没有被检查。


20

$("#locationthemes").prop("checked")


1
这应该是一个注释。 - Gajendra K Chauhan

14

使用jquery的map函数

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

在这个例子中,应该将checkboxName命名为“locationthemes”。 - hrabinowitz

8

更现代的做法:

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

我们首先找到所有具有给定名称的选中复选框,然后jQuery的map()函数迭代每一个选中复选框,在回调函数上调用它以获取值,并将结果作为新的jQuery集合返回,这个集合保存了复选框的值。然后我们调用get()方法获得值的数组,再使用join()方法将它们连接成一个单一的字符串-最终将其赋值给常量selectedValues。

6
var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
     SlectedList.push($(this).val());
});

1
请在您的答案中提供解释。 - Word Rearranger

5
You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();

1
如何将此结果分配给变量? - Mano Johnbritto

3

因此,全部在一行:

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

关于选择器 [id*="checkbox"] 的说明,它将获取任何包含字符串 "checkbox" 的项目。 这里有点笨拙,但如果您想从类似 .NET CheckBoxList 的东西中提取选定的值,则非常好。 在这种情况下, "checkbox" 将是您给 CheckBoxList 控件命名的名称。


1
这很有用 @mike - Yii2Developer

2

来源 - 更多细节

使用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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接