jQuery 获取选中复选框的总数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17084505/
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
Getting total number of checked checkboxes
提问by Alan A
I have a form with checkboxes with the input being stored in an array:
我有一个带有复选框的表单,输入存储在一个数组中:
<input type="checkbox" name="lineup[]" value="1">Tom</input>
<input type="checkbox" name="lineup[]" value="2">David</input>
<input type="checkbox" name="lineup[]" value="3">Sarah</input>
Using jQuery I want to find how many checkboxes are ticked/checked:
使用 jQuery 我想找到多少个复选框被勾选/选中:
var total=$(this).find('input[name=lineup]').serialize();
alert(total.length);
However the total is always output a 0. What am I doing wrong?
但是总数总是输出 0。我做错了什么?
Thanks,
谢谢,
Alan.
艾伦。
回答by MrCode
Use :checked
in the selector, and don't serialize it, just get the length.
:checked
在选择器中使用,不要序列化它,只获取长度。
var total=$(this).find('input[name="lineup[]"]:checked').length;
Also use []
in the selector, because your checkboxes use []
in the name. As @Felix Klingpoints out, it is part of the name and so you have to explicitly specify the []
.
也在[]
选择器中使用,因为您的复选框[]
在名称中使用。正如@Felix Kling指出的那样,它是名称的一部分,因此您必须明确指定[]
.
回答by bipen
try this
尝试这个
alert($('input[name=lineup]:checked').length);
your way
你的方式
$(this).find('input[name=lineup]:checked').length;
回答by Yannis
How about:
怎么样:
var checkedBoxes = $('input[name=lineup]:checked').length;
alert(checkedBoxes);