Explain Codes LogoExplain Codes Logo

Setting "checked" for a checkbox with jQuery

javascript
jquery
checkbox
javascript-advanced
Anton ShumikhinbyAnton Shumikhin·Nov 6, 2024
TLDR

In jQuery, here's how to toggle a checkbox's state:

$('#checkboxId').prop('checked', true); // Checks it $('#checkboxId').prop('checked', false); // Checks out... literally

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():

$('#checkboxId').attr('checked', 'checked'); // Old school check

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:

$('.myCheckbox').prop('checked', true); // Checks all (aka power move) $('.myCheckbox').prop('checked', false); // Unchecks all (aka cold heart)

To add some custom logic, go with the .each() method:

$('.myCheckbox').each(function() { this.checked = true; // Or apply a condition based on `this` });

Detective work: Is it checked?

To determine if a checkbox is checked or just chilling:

var isChecked = $('#checkboxId').is(':checked'); // Spill the beans!

That's a boolean for your if-else troubles!

Fancy flipping: Dynamic toggling

To toggle the state based on the current vibe:

$('#checkboxId').prop('checked', function(i, value) { return !value; // Life's a switch, huh? });

Tick the box, ring the bell: Trigger a click event

For a more interactive check:

$('#checkbox').click(); // Just as if a human did it

And for our checkbox party:

$(".myCheckbox").each(function() { $(this).click(); // Cause a stir! });

But remember: .click() might trigger attached event handlers.

Your own rules: Custom plugin

You can write a custom jQuery plugin for depth and fun:

$.fn.checked = function(value) { return this.each(function() { this.checked = value; // Now that's what I call power! }); }; // Usage: $('.myCheckbox').checked(true); // Checks all

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.