How to check and uncheck a checkbox with jQueryHow 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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus