Monday, October 17, 2011

Determining if a Checkbox is Checked Using jQuery

A checkbox can be checked initially by using

<input type="checkbox" id="yourCheckBox" name="yourCheckBox" checked="checked" />

or

$("#yourCheckBox").attr('checked', true);


When one of the code above is used, the following two lines of code can fail in retrieving the correct value of the checkbox:

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

and

$('#yourCheckBox').val()


A better way is to use the following jQuery code instead:

$('#yourCheckBox').is(":checked")

My office mate and I took almost an hour to figure out that bug in our project code.

No comments:

Post a Comment