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

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"

Uncheck a checkbox (the right way)

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

// Remove the checkbox

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

Many of these strategies also work in QueryPath.