Using Jquery to Check a Checkbox

Published on Sep 27, 2012 by Jamie Munro

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:


if ($('#idOfCheckBox').is(':checked')) {
alert('Checked!');
} else {
alert('Not checked!');
}


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:


// 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!');
}


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".

Tags: jquery | attr | prop | is | jQuery

Related Posts

blog comments powered by Disqus