Setting "checked" for a checkbox with jQuery
In jQuery, here's how to toggle a checkbox's state:
Replace #checkboxId
with your actual checkbox's ID. Reach for .prop()
when dealing with dynamic properties like checked
.
Advanced toggling: Power moves
For the nostalgics: Pre-1.6 jQuery
Back in the day (pre-1.6 versions), we had to lean on attr()
:
In jQuery 1.6+ though, prop()
is what you need. It helps prevent confusing static HTML attributes with dynamic properties.
Checkboxes gone wild: Bulk actions
If you have multiple checkboxes (aka a form), you can still manage them all at once:
To add some custom logic, go with the .each()
method:
Detective work: Is it checked?
To determine if a checkbox is checked or just chilling:
That's a boolean for your if-else troubles!
Fancy flipping: Dynamic toggling
To toggle the state based on the current vibe:
Tick the box, ring the bell: Trigger a click event
For a more interactive check:
And for our checkbox party:
But remember: .click()
might trigger attached event handlers.
Your own rules: Custom plugin
You can write a custom jQuery plugin for depth and fun:
Hello, .checked()
. Welcome to the jQuery prototype!
Pitstop: Things to watch out
Friend or foe: Form reset conflicts
.removeAttr('checked')
can play a messy game with your form resets. Better use .prop('checked', false)
to keep things clean.
Now you're just making stuff up: Invalid methods
Beware of fakes! .checked(true)
or .selected(true)
are not even a thing in jQuery. Always ring .prop()
for manipulating checkbox.
Name it like Beckham: Avoid name clashes
Craft unique names for your custom method to avoid future collisions with native or plugin jQuery methods.
The good, the bad, and the browser: Cross-browser compatibility
The checked
property is your most reliable ally when it comes to browser compatibility.
Was this article helpful?