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

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:

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

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

*update 27/07/2011*

Use the new .prop() function:

$(".myCheckbox").prop("checked", true);
$(".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)

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

and un-checking (by removing the attribute entirely)

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

Sources

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