62

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 can this be done with jQuery?

starball
  • 20,030
  • 7
  • 43
  • 238
daGrevis
  • 21,014
  • 37
  • 100
  • 139

5 Answers5

178

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;
Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
19

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
Ramzan Mahmood
  • 1,881
  • 2
  • 21
  • 46
18

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;
Gunaseelan
  • 2,494
  • 5
  • 36
  • 43
Nguyễn Thành Bồi
  • 2,457
  • 2
  • 14
  • 8
6

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);
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Hasnain Mehmood
  • 407
  • 5
  • 4
2

You can do it by using name attibute, class, id or just universal checkbox; 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;

Complete code

$('checkbox.className').blur(function() {
    //count only checked checkbox 
    $('checkbox[name=myAllcheckBoxName]:checked').length;
});
Maxime
  • 838
  • 6
  • 18
CodeLover
  • 151
  • 1
  • 7