jQuery 如何使用jQuery计算复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8011556/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 09:53:01  来源:igfitidea点击:

How to count check-boxes using jQuery?

jquerycheckboxcountchecked

提问by daGrevis

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? Thanks in advance!

如何用 jQuery 做到这一点?提前致谢!

回答by Nicola Peluchetti

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;

回答by Nguy?n Thành B?i

The following code worked for me.

以下代码对我有用。

$('input[name="chkGender[]"]:checked').length;

回答by Samuel Aiala Ferreira

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 exampleclass='mycxk'and you can count that using the filter, like this

例如class='mycxk',您可以使用过滤器来计算,就像这样

$('.mycxk').filter(':checked').length

回答by Hasnain Mehmood

There are multiple methods to do that:

有多种方法可以做到这一点:

Method 1:

方法一:

alert($('.checkbox_class_here:checked').size());

Method 2:

方法二:

alert($('input[name=checkbox_name]').attr('checked'));

Method 3:

方法三:

alert($(":checkbox:checked").length);

回答by CodeLover

You can do it by using name attibute, class, id or just universal checkbox; If you want to count only checkednumber of checkbox.

您可以通过使用名称属性、类、ID 或仅使用通用复选框来实现;如果您只想计算复选框的选中数量。

By the class name :

按班级名称:

var countChk = $('checkbox.myclassboxName:checked').length;

By name attribute :

按名称属性:

var countByName= $('checkbox[name=myAllcheckBoxName]:checked').length;

Complete code

完整代码

$('checkbox.className').blur(function() {
    //count only checked checkbox 
    $('checkbox[name=myAllcheckBoxName]:checked').length;
});