How to count check-boxes using jQuery?
Asked Answered
L

5

64

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?

Latty answered 4/11, 2011 at 15:18 Comment(0)
L
179

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;
Lenny answered 4/11, 2011 at 15:19 Comment(0)
S
20

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
Shuck answered 27/8, 2016 at 1:55 Comment(3)
I prefer this answer in my case because I can define the let myCheckboxList = $('.mycxk'); to reuse it after this myCheckboxList.filter(':checked').length.Xanthin
I also liked this answerFardel
this answer is good, i want count input with class :))Shingle
E
18

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;
Electroscope answered 30/6, 2015 at 11:6 Comment(0)
O
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);
Oscilloscope answered 9/1, 2017 at 6:57 Comment(0)
O
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;
});
Omni answered 17/4, 2019 at 2:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.