jQuery Checkboxes: Checking and unchecking the right way

Sep 3 2010

When working with checkboxes in jQuery and JavaScript, sometimes all you really want to do is toggle the checked state of the checkbox. There are many examples of strange ways of accomplishing this, many of which are wrong or will only work on some browsers. Here is a correct (XHTML-correct) and compact way of doing this.

Check to see if a checkbox is checked

// Returns a boolean, true if checked, false otherwise
jQuery('#my-checkbox').is(':checked');

Check a checkbox

Following the HTML spec, the attribute must be set to checked="checked"; not just checked or checked="true", etc.

// This sets the attribute checked="checked"
jQuery('#my-checkbox').attr('checked','checked');

Uncheck a checkbox (the right way)

To uncheck the checkbox, you need to remove the checked attribute.

// Remove the checkbox
jQuery('#my-checkbox').removeAttr('checked');

Uncheck all checkboxes

We can combine strategies to check or uncheck all checkboxes.

// Check anything that is not already checked:
jQuery(':checkbox:not(:checked)').attr('checked', 'checked');

// Remove the checkbox
jQuery(':checkbox:checked').removeAttr('checked');

Many of these strategies also work in QueryPath.



comments powered by Disqus