[jquery] Check if all checkboxes are selected

How do I check if all checkboxes with class="abc" are selected?

I need to check it every time one of them is checked or unchecked. Do I do it on click or change?

This question is related to jquery

The answer is


$('input.abc').not(':checked').length > 0

You can use change()

$("input[type='checkbox'].abc").change(function(){
    var a = $("input[type='checkbox'].abc");
    if(a.length == a.filter(":checked").length){
        alert('all checked');
    }
});

All this will do is verify that the total number of .abc checkboxes matches the total number of .abc:checked.

Code example on jsfiddle.


Part 1 of your question:

var allChecked = true;
$("input.abc").each(function(index, element){
  if(!element.checked){
    allChecked = false;
    return false;
  } 
});

EDIT:

The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.


Alternatively, you could have also used every():

// Cache DOM Lookup
var abc = $(".abc");

// On Click
abc.on("click",function(){

    // Check if all items in list are selected
    if(abc.toArray().every(areSelected)){
        //do something
    }

    function areSelected(element, index, array){
        return array[index].checked;
    }
});

This is how I achieved it in my code:

if($('.citiescheckbox:checked').length == $('.citiescheckbox').length){
    $('.citycontainer').hide();
}else{
    $('.citycontainer').show();
}

A class independent solution

var checkBox = 'input[type="checkbox"]';
if ($(checkBox+':checked').length == $(checkBox).length) {
   //Do Something
}

The search criteria is one of these:

input[type=checkbox].MyClass:not(:checked)
input[type=checkbox].MyClass:checked

You probably want to connect to the change event.


$('.abc[checked!=true]').length == 0