[英]How to count check-boxes using jQuery?
I have tons of checkboxes that are either checked ( checked="checked"
) or unchecked. 我有大量复选框,要么选中(
checked="checked"
),要么取消选中。
I would like to get the number of all checkboxes, unchecked and checked checkboxes. 我想获取所有复选框的数量,取消选中并选中复选框。
With check-box I mean <input type="checkbox" />
. 带复选框的意思是
<input type="checkbox" />
。
How to do it with jQuery? 如何用jQuery做到这一点? Thanks in advance!
提前致谢!
You could do: 你可以这样做:
var numberOfChecked = $('input:checkbox:checked').length;
var totalCheckboxes = $('input:checkbox').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;
EDIT 编辑
Or even simple 甚至简单
var numberNotChecked = $('input:checkbox:not(":checked")').length;
以下代码对我有用。
$('input[name="chkGender[]"]:checked').length;
Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked. 假设您有一个包含多个复选框的tr行,并且只有在选中第一个复选框时才想要计数。
You can do that by giving a class to the first checkbox 你可以通过给第一个复选框提供一个类来实现
For example class='mycxk'
and you can count that using the filter, like this 例如
class='mycxk'
,您可以使用过滤器计算,就像这样
$('.mycxk').filter(':checked').length
There are multiple methods to do that: 有多种方法可以做到这一点:
Method 1: 方法1:
alert($('.checkbox_class_here:checked').size());
Method 2: 方法2:
alert($('input[name=checkbox_name]').attr('checked'));
Method 3: 方法3:
alert($(":checkbox:checked").length);
You can do it by using name attibute, class, id or just universal checkbox; 您可以使用名称attibute,class,id或只是通用复选框; If you want to count only checked number of checkbox.
如果您只想计算已选中的复选框数。
By the class name : 按类名:
var countChk = $('checkbox.myclassboxName:checked').length;
By name attribute : 按名称属性:
var countByName= $('checkbox[name=myAllcheckBoxName]:checked').length;
$('checkbox.className').blur(function() {
//count only checked checkbox
$('checkbox[name=myAllcheckBoxName]:checked').length;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.