Javascript 我如何计算使用 jQuery 在页面上选择了多少个复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4796036/
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
How do I count how many checkboxes are selected on a page with jQuery
提问by Vivian River
I want to count how many checkboxes on my page are selected using jQuery. I've written the following code:
我想计算我的页面上使用 jQuery 选择了多少个复选框。我编写了以下代码:
var numberOfCheckboxesSelected = 0;
$(':checkbox').each(function(checkbox) {
if (checkbox.attr('checked'))
numberOfCheckboxesSelected++;
});
However, my code errors out with the message "Object doesn't support this property or method" on the third line.
但是,我的代码在第三行出现错误消息“对象不支持此属性或方法”。
How do I count how many checkboxes are selected on my page?
如何计算我的页面上选中了多少个复选框?
回答by Stephen
jQuery supports the :checked
pseudo-selector.
jQuery 支持:checked
伪选择器。
var n = $("input:checked").length;
This will work for radio buttons as well as checkboxes. If you just want checkboxes, but also have radio buttons on the page:
这适用于单选按钮和复选框。如果您只想要复选框,而且页面上还有单选按钮:
var n = $("input:checkbox:checked").length;
回答by Chandu
Try this(to avoid counting any selected radio buttons):
试试这个(以避免计算任何选定的单选按钮):
var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length;
回答by lonesomeday
The first argument passed to the callback in each
is the index, not the element. You should use this
or a second argument:
传递给回调的第一个参数each
是索引,而不是元素。您应该使用this
或第二个参数:
$(':checkbox').each(function(idx, checkbox) {
if (checkbox.attr('checked'))
numberOfCheckboxesSelected++;
});
Moreover, the easier way to do this is to select only the checked elements with the :checked
selector and then check the selection's length
property:
此外,更简单的方法是使用选择器只选择选中的元素,:checked
然后检查选择的length
属性:
var numberOfCheckboxesSelected = $('input:checkbox:checked').length;
回答by derek
$("input:checked").length
this will return the count of checked checkboxes.
这将返回选中复选框的计数。