Explain Codes LogoExplain Codes Logo

Check/uncheck checkbox with JavaScript

javascript
event-listeners
checkboxes
user-experience
Nikita BarsukovbyNikita Barsukov·Jan 21, 2025
TLDR

Jump directly into the action by manipulating a checkbox's checked attribute:

// Checking a checkbox like a boss document.querySelector('#myCheckbox').checked = true; // Unchecking a checkbox like a villain document.querySelector('#myCheckbox').checked = false;

Translate true or false into a checked state to shift "the reality program" of your checkbox.

Working deep with checkboxes

Master more complex checkbox manipulations through diverse methods:

User simulation with click()

Simulate user interaction, by invoking the checkbox's click event:

var checkbox = document.getElementById('myCheckbox'); checkbox.click(); // The checkbox just got clicked (boom! 💥)

Supporting Sir Old Browser

For those visiting from "the land of the lost browsers", use setAttribute & removeAttribute:

var checkbox = document.getElementById('myCheckbox'); // Old browser says "Yeah, I checked that for you" 😎 checkbox.setAttribute('checked', checkbox.checked ? '' : 'checked'); // Old browser says "It's gone, just like my last update" 😅 checkbox.removeAttribute('checked');

Riding the jQuery wave

In the world of jQuery, .prop() is your magic wand for state changes:

// jQuery gets it checked without breaking a sweat $('#myCheckbox').prop('checked', true); // jQuery makes it unchecked, voila! 🎩🐇 $('#myCheckbox').prop('checked', false);

Time traveling to jQuery versions below 1.6:

// Checking with classical jQuery $('#myCheckbox').attr('checked', 'checked'); // Uncorking the unchecked state with classic jQuery $('#myCheckbox').removeAttr('checked');

Pro level tricks with checkboxes

User experience - A guiding light

Always make your checkmarks visible and accessible. Use proper aria attributes and provide visual confirmation of state changes. UI ninjas keep their users informed.

Being dynamic with addEventListener

document.getElementById('myCheckbox').addEventListener('change', function(event) { // The code that runs when reality shifts });

Use addEventListener to ride the change wave every time the checkbox state changes.

Handling an army of checkboxes

In scenarios with multiple checkboxes (we're looking at you, email clients):

// The coding Thanos snaps his fingers, and all checkboxes get checked document.querySelectorAll('.checkbox-class').forEach(function(checkbox) { checkbox.checked = true; }); // With another snap, they all get unchecked document.querySelectorAll('.checkbox-class').forEach(function(checkbox) { checkbox.checked = false; });