How to count check-boxes using jQuery?

2019-01-21 12:39发布

I have tons of checkboxes that are either checked (checked="checked") or unchecked.

I would like to get the number of all checkboxes, unchecked and checked checkboxes.

With check-box I mean <input type="checkbox" />.

How to do it with jQuery? Thanks in advance!

4条回答
Juvenile、少年°
2楼-- · 2019-01-21 13:16

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);
查看更多
放我归山
3楼-- · 2019-01-21 13:18

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;
查看更多
爷的心禁止访问
4楼-- · 2019-01-21 13:30

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;
查看更多
SAY GOODBYE
5楼-- · 2019-01-21 13:40

Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked.

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

$('.mycxk').filter(':checked').length
查看更多
登录 后发表回答