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?
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?
I think the easiest way is checking for this condition:
$('.abc:checked').length == $('.abc').length
You could do it every time a new checkbox is checked:
$(".abc").change(function(){
if ($('.abc:checked').length == $('.abc').length) {
//do something
}
});
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.
A class independent solution
var checkBox = 'input[type="checkbox"]';
if ($(checkBox+':checked').length == $(checkBox).length) {
//Do Something
}
Part 1 of your question:
var allChecked = true;
$("input.abc").each(function(index, element){
if(!element.checked){
allChecked = false;
return false;
}
});
EDIT:
The (above answer) 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();
}
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.