jQuery check if checkbox is checked or not

· kalpesh

jQuery javascript frameworkUsing jQuery, check whether checkbox is checked or not using 4 different ways in this post.

Below code relies on jQuery’s is method to check if the checkbox is checked or not. If you want to lookup the checkbox by class instead of id, just replace #yourCheckboxID with .yourCheckboxClassName

if($(‘#yourCheckboxID).is(:checked)) {  
 //do whatever you want here, checkbox is checked  
} else {  
 //do whatever you want here, checkbox is NOT checked  
}

Other alternative to check same thing:

$(‘#yourCheckboxID).change(function() {  
 if(this.checked) {  
 //checkbox is checked  
 } else {  
 //checkbox is NOT checked  
 }  
});

Above code is the better way and my favorite. It will simply observe the checkbox and when it’s “changed”, the above function will get triggered. Once triggered, it will check the changed object’s (checkbox) attribute “checked”. If it finds the attribute is set, then returns true otherwise returns false.

Third way of doing it is:

if($(‘#yourCheckboxID).attr(checked) {  
 //checkbox is checked  
} else {  
 //checkbox is NOT checked  
}

Above code will check the checkbox’s attribute “checked”, if present it will give true and if not present, it will give false.

Since jQuery 1.6, the new method has been introduced which is called prop. If you are using jQuery 1.6 or above, you can use following code to check if checkbox is checked or not:

if($(‘#yourCheckboxID).prop(checked)) {  
 //checkbox is checked  
} else {  
 //checkbox is NOT checked  
}

#checkbox #jquery