jQuery: Check if a checkbox is checked or set the checked state

0 Comments

To test if a checkbox has been ticked is a bit tricky.

Using val() will return the potential value of the checkbox, regardless of its check state.

Instead, use the following line to test its state:

1.$("#checkbox").attr('checked')

This will return true or false depending on its checked state.

*update 27/07/2011*

Use the new .prop() function:

1.$(".myCheckbox").prop("checked", true);
2.$(".myCheckbox").prop("checked", false);

jQuery 1.5 and below

The .prop() function is not available so you need to use .attr().

To tick the checkbox (by setting the value of the checked attribute)

1.$('.myCheckbox').attr('checked', 'checked')

and un-checking (by removing the attribute entirely)

1.$('.myCheckbox').removeAttr('checked')

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog