所有选中复选框的 jQuery 数组(按类)

可能的复制品:
使用 jQuery 选择复选框组的值

在 HTML 中,我用一个类将一组复选框组合在一起。我想在 jQuery 中获得一个数组,其中包含为该类选中/选中的所有复选框(因此页面上的其他复选框将被忽略)。

HTML 代码如下:

<input type="checkbox" class="group1" value="18" checked="checked" />
<input type="checkbox" class="group1" value="20" />
<input type="checkbox" class="group1" value="15" />
<input type="checkbox" class="group2" value="14" />
<input type="checkbox" class="group1" value="55" checked="checked" />
<input type="checkbox" class="group1" value="10" checked="checked" />
<input type="checkbox" class="group2" value="77" checked="checked" />
<input type="checkbox" class="group1" value="11" />

将选中/选中的 group1复选框的值返回到一个数组,如下所示:

var values = [ 18, 55, 10 ];
136919 次浏览
var matches = [];
$(".className:checked").each(function() {
matches.push(this.value);
});

You can use the :checkbox and :checked pseudo-selectors and the .class selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.

Then you can easily use the Traversing/map method to get an array of values:

var values = $('input:checkbox:checked.group1').map(function () {
return this.value;
}).get(); // ["18", "55", "10"]

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})