How to check and uncheck a checkbox with jQueryHow to check and uncheck a checkbox with jQuery

Posted November 14th, 2008 in Javascript (Updated September 14th, 2010)

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.

Example form

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.

Check if the checkbox is 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')

Set the checkbox to checked or not checked

The status of the checkbox can be changed 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);

Working example

And finally, here's the example form in action:

A note about boolean values

There is a discussion in the comments below about issues found with Chromium which may be related to string values of true and false being passed whereas it needs to be strictly a boolean true or false otherwise unexpected consequences can happen.

It has been suggested to use .removeAttr() instead but this may have other consequences from my reading of the comments on the jQuery documentation page for the function. I will follow up this post at a later date and do more testing to confirm for sure

Toggling a checkbox when clicking a label

Note that Javascript is not required to toggle a checkbox when clicking some text; that's what HTML <label>s are for. Have a read of my follow up post using HTML <label> to toggle and select fields for more information.

Related posts:

Comments

blog comments powered by Disqus