Determine if checkbox is checked in jQuery

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

As this is an often asked question, in this tutorial we will show you how to determine if a particular checkbox is checked in jQuery.

Consider the following user interface …

simple checkbox

with the following HTML…

checkbox html

You want to determine if the “coffee” checkbox is checked.

The proper way is to add this jQuery code at the bottom of the page …

checkbox selected

Note that we used the prop method as in …

// check if coffee is selected
if ( $('input[value=coffee]').prop("checked") ) {
    alert("coffee is selected");

This finds the checkbox input with the value=coffee and test if the property is checked.

Do not use the attr() method to check if checkbox is checked.

Do not use the attr() method.  The attr() looks only for the attribute “checked” in the hardcoded HTML.  It does not look for the checked state.  If you do this …

// this will not work as intended
if ( $('input[value=coffee]').attr("checked") ) {
    alert("coffee is selected");

It will not work.

The jQuery API documentation writes …

“To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.”

To check if at least one of the check boxes is selected, you can do …

if ( $('input[name=beverages]:checked').length > 0 ) {
    alert("at least one checkbox selected");

This queries for all elements with name=beverages that is checked.  If found at least one, if condition is true.