May 29, 2013
kalpesh

jQuery check if checkbox is checked or not

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

1
2
3
4
5
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:

1
2
3
4
5
6
7
$('#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:

1
2
3
4
5
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:

1
2
3
4
5
if($('#yourCheckboxID').prop('checked')) {
    //checkbox is checked
} else {
    //checkbox is NOT checked
}

Leave a comment

 

Welcome to my Blog

Kalpesh MehtaHelping Magento developers in their day-to-day development problems since 2011. Most of the problems and solutions here are my own experiences while working on different projects. Enjoy the blog and don't forget to throw comments and likes/+1's/tweets on posts you like. Thanks for visiting!

Certifications