Javascript 所有选定复选框的 jQuery 数组(按类)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2099164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Array of all selected checkboxes (by class)
提问by leepowers
Possible Duplicate:
Select values of checkbox group with jQuery
可能的重复:
使用 jQuery 选择复选框组的值
In HTML I have a set of checkboxes grouped together by a class. I want to get an array in jQuery containing all the checkboxes that are selected/checked for that class (so other checkboxes on the page are ignored).
在 HTML 中,我有一组按类分组的复选框。我想在 jQuery 中获取一个数组,其中包含为该类选择/选中的所有复选框(因此页面上的其他复选框将被忽略)。
So HTML code like this:
所以 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" />
Would return the values of the checked/selected group1checkboxes into an array like this:
将选中/选中group1复选框的值返回到这样的数组中:
var values = [ 18, 55, 10 ];
回答by CMS
You can use the :checkboxand :checkedpseudo-selectors and the .classselector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.
您可以使用:checkbox和:checked伪选择器和.class选择器,这样您将确保获得正确的元素,仅选中您指定的类的复选框。
Then you can easily use the Traversing/mapmethod to get an array of values:
然后你可以很容易地使用Traversing/map方法来获取一个值数组:
var values = $('input:checkbox:checked.group1').map(function () {
return this.value;
}).get(); // ["18", "55", "10"]
回答by Anurag
var matches = [];
$(".className:checked").each(function() {
matches.push(this.value);
});
回答by Artemk
You can also add underscore.jsto your project and will be able to do it in one line:
您还可以将underscore.js添加到您的项目中,并且可以在一行中完成:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

