JavaScript
Checkbox
Web Development
Programming
Front-end Development

Check or uncheck a checkbox with JavaScript

Codemia Knowledge Hub ·

To check or uncheck a checkbox in JavaScript, set its checked property to true or false. Use the DOM property, not the HTML attribute: user clicks change the property at runtime, while the attribute keeps its initial markup value.

javascript
1const checkbox = document.getElementById('subscribe');
2
3checkbox.checked = true;   // check it
4checkbox.checked = false;  // uncheck it

Checking and unchecking a single checkbox

Start with a checkbox in HTML:

html
<input type="checkbox" id="subscribe" />
<label for="subscribe">Subscribe to newsletter</label>

Get the element and set checked:

javascript
1const checkbox = document.getElementById('subscribe');
2
3// Check it
4checkbox.checked = true;
5
6// Uncheck it
7checkbox.checked = false;

This is the standard browser API. It works in every modern browser with no libraries. Make sure the script runs after the element exists: in the <head> without defer or a DOMContentLoaded handler, getElementById returns null.

Toggling a checkbox

Negate the property to flip the current state:

javascript
const checkbox = document.getElementById('subscribe');
checkbox.checked = !checkbox.checked;

This is useful when another control drives the checkbox, such as a button or a keyboard shortcut handler:

html
<input type="checkbox" id="darkMode" />
<label for="darkMode">Dark mode</label>
<button id="toggleBtn">Toggle dark mode</button>
javascript
1const checkbox = document.getElementById('darkMode');
2const toggleBtn = document.getElementById('toggleBtn');
3
4toggleBtn.addEventListener('click', () => {
5    checkbox.checked = !checkbox.checked;
6});

Toggling from JavaScript does not fire the change event. If your code relies on change listeners, dispatch the event yourself, as shown next.

Reacting to user changes with the change event

When a user clicks a checkbox, the browser fires change:

javascript
1const checkbox = document.getElementById('subscribe');
2
3checkbox.addEventListener('change', () => {
4    if (checkbox.checked) {
5        console.log('User subscribed');
6    } else {
7        console.log('User unsubscribed');
8    }
9});

This is the standard pattern for forms, feature toggles, consent banners and filter UIs. By default change fires only on user interaction. If you set checked in code and need the listener to run, dispatch the event:

javascript
checkbox.checked = true;
checkbox.dispatchEvent(new Event('change'));

Checking or unchecking a group of checkboxes

Query a group together instead of handling each element:

html
<input type="checkbox" class="feature" value="notifications" />
<input type="checkbox" class="feature" value="analytics" />
<input type="checkbox" class="feature" value="exports" />

Check all of them:

javascript
1const boxes = document.querySelectorAll('.feature');
2boxes.forEach(box => {
3    box.checked = true;
4});

Uncheck all of them:

javascript
boxes.forEach(box => {
    box.checked = false;
});

Collect the values of the checked boxes only:

javascript
1const selected = [...document.querySelectorAll('.feature:checked')]
2    .map(box => box.value);
3
4console.log(selected); // e.g., ["notifications", "exports"]

The :checked pseudo-selector lets querySelectorAll select by current state, so you do not have to loop and inspect each element.

Select all / deselect all

A "select all" checkbox controlling a group of child checkboxes is common in admin dashboards, email clients and bulk-action tables:

html
1<input type="checkbox" id="selectAll" />
2<label for="selectAll">Select all</label>
3
4<input type="checkbox" class="row-item" value="1" />
5<input type="checkbox" class="row-item" value="2" />
6<input type="checkbox" class="row-item" value="3" />
javascript
1const selectAll = document.getElementById('selectAll');
2const items = document.querySelectorAll('.row-item');
3
4// When "select all" changes, sync all children
5selectAll.addEventListener('change', () => {
6    items.forEach(item => {
7        item.checked = selectAll.checked;
8    });
9});
10
11// When any child changes, update "select all" state
12items.forEach(item => {
13    item.addEventListener('change', () => {
14        selectAll.checked = [...items].every(i => i.checked);
15    });
16});

The second listener is the one people forget. Without it, "select all" stays checked after a user unchecks a single row, so the UI shows the wrong state.

Why setAttribute('checked') is wrong

A common mistake:

javascript
// Do NOT use this for runtime state changes
checkbox.setAttribute('checked', 'checked');

This changes the HTML attribute, not the DOM property. Once a user interacts with the checkbox, the two diverge: the checked property tracks the live state, while the attribute only reflects the initial value from markup.

ApproachControlsTracks User Interaction
checkbox.checked = trueDOM propertyYes
checkbox.setAttribute('checked', '')HTML attributeNo
checkbox.removeAttribute('checked')HTML attributeNo

Use the property for runtime behavior. The attribute only matters for the initial HTML render.

Requiring a checkbox before form submission

A typical use is requiring a terms-of-service checkbox before the form submits:

html
1<form id="signupForm">
2    <label>
3        <input type="checkbox" id="terms" />
4        I accept the terms and conditions
5    </label>
6    <button type="submit">Create account</button>
7</form>
javascript
1document.getElementById('signupForm').addEventListener('submit', event => {
2    const terms = document.getElementById('terms');
3    if (!terms.checked) {
4        event.preventDefault();
5        alert('Please accept the terms first.');
6    }
7});

This reads the live checked property right before the form submits. For simple cases HTML can do this without JavaScript: the required attribute enforces the checkbox on submission, and a <label> already toggles its associated checkbox. Reach for JavaScript only when you need more than that.

Dynamically rendered checkboxes

When checkboxes are rendered dynamically (client-side templates, API responses, framework rendering), watch for stale references. The NodeList returned by querySelectorAll is static, so checkboxes added to the DOM later will not be in a cached result.

One fix is to re-query inside the event handler:

javascript
1selectAll.addEventListener('change', () => {
2    const items = document.querySelectorAll('.row-item');
3    items.forEach(item => {
4        item.checked = selectAll.checked;
5    });
6});

The other is event delegation on a parent container:

javascript
1document.getElementById('tableBody').addEventListener('change', event => {
2    if (event.target.classList.contains('row-item')) {
3        const allItems = document.querySelectorAll('.row-item');
4        selectAll.checked = [...allItems].every(i => i.checked);
5    }
6});

Event delegation is usually the better choice for dynamic content because it scales without re-binding listeners.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms