How to check and uncheck a checkbox with jQuery
Posted November 14th, 2008 in Javascript
jQuery is a Javascript framework which can simplify coding Javascript for a website and removes a lot of cross browser compatibility issues. Yesterday I looked at how to get and set form element values with jQuery but didn't deal with checkboxes. Today's post looks at how to tell if an HTML form checkbox is checked or not checked with jQuery and then how to change it to be un/checked.
Our example form looks like this:
<input type="checkbox" name="foo" value="bar" /> <input type="button" onclick="show_checked()" value="Show" /> <input type="button" onclick="set_checked(true)" value="On" /> <input type="button" onclick="set_checked(false)" value="Off" />
There's checkbox with name "foo" and then three buttons. The first calls a functionto show us if the checkbox is checked or not, and the second two change it from being checked to not being checked.
There are several ways to get to work out if a checkbox is checked or not with jQuery, and here a couple of alternatives. Each will return true if it's checked or false if it's not.
$('input[name=foo]').is(':checked')
$('input[name=foo]').attr('checked')
We can change the status of the checkbox using the attr() function like so, to check the box:
$('input[name=foo]').attr('checked', true);
and like so to uncheck the box:
$('input[name=foo]').attr('checked', false);
And finally, here's the example form in action:
Please note that if you're viewing this post in an RSS reader or email then the form won't work. You'll need to open this post in your web browser by clicking here.
Related posts:
- Running a function with jQuery when the window is resized (Tuesday, August 25th 2009)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)
- Adding, removing and checking if an element has a CSS class with jQuery (Tuesday, December 16th 2008)
- How to get and set form element values with jQuery (Thursday, November 13th 2008)
- Style an HTML form input with CSS and jQuery (Saturday, July 26th 2008)
- Clearing the default value of text input with Javascript (Tuesday, June 17th 2008)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
