You can use jQuery to check if a checkbox is checked. You can either use the prop() method in jQuery 1.7 or the attr() method in lower versions. We will also show you how to use the :checked selector to achieve the same result.
jQuery 1.7+
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
console.log("Checkbox is checked.");
}
else if($(this).prop("checked") == false){
console.log("Checkbox is unchecked.");
}
});
});
Lower than jQuery 1.7
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).attr("checked") == true){
console.log("Checkbox is checked.");
}
else if($(this).attr("checked") == false){
console.log("Checkbox is unchecked.");
}
});
});
You can also use the jQuery :checked selector to check if the checkbox is checked using the following example.
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).is(":checked")){
console.log("Checkbox is checked.");
}
else if($(this).is(":not(:checked)")){
console.log("Checkbox is unchecked.");
}
});
});
Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.