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.
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:
and like so to uncheck the box:
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
- Running a function with jQuery when the window is resized
- Dynamically get and set an elements content with jQuery
- Adding, removing and checking if an element has a CSS class with jQuery
- How to get and set form element values with jQuery
- Style an HTML form input with CSS and jQuery