Using Jquery to Check a Checkbox Using Jquery to Check a Checkbox

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

Published on Sep 27, 2012

Tags: prop | jQuery Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.