Using Jquery to Check a Checkbox

U

This is an excellent follow up on a recent post – Determine if an element is visible with Jquery – because in that post we use the is Jquery operator to check if an item is visible or hidden.

Spoiler alert, in this article, we can leverage the exact same function by altering the value of the selector passed into it.

 
At the end of the day, the code is quite simple:

[code]
if ($(‘#idOfCheckBox’).is(‘:checked’)) {
alert(‘Checked!’);
} else {
alert(‘Not checked!’);
}
[/code]

There are a few other ways to do it as well.  Pre Jquery 1.7, you could use the attr function.  Jquery 1.7+ you would have to use the prop attribute.  This is done as follows:

[code]
// Pre 1.7
if ($(‘#idOfCheckBox’).attr(‘checked’)) {
alert(‘Checked!’);
} else {
alert(‘Not checked!’);
}

// 1.7+
if ($(‘#idOfCheckBox’).prop(‘checked’)) {
alert(‘Checked!’);
} else {
alert(‘Not checked!’);
}
[/code]

Both of these functions return true or false based on if the item is checked or not.  At the end of the day, it’s 6 to 1 half dozen the other.  However, if I had to pick, I once again like the idea of using the is function.  It seems slightly more “readable”.

About the author

By Jamie

My Books