Check/Uncheck checkbox with JavaScript
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To check or uncheck a checkbox with JavaScript, set its checked property to true or false. This is the DOM property, not the HTML attribute, and the distinction matters because user interaction modifies the property at runtime while the attribute stays frozen at its initial markup value.
That single property is the foundation for every checkbox operation you will ever write in plain JavaScript. The rest of this article covers toggling, event handling, group operations, and the patterns that trip developers up most often.
Checking and Unchecking a Single Checkbox
Start with a basic checkbox element in HTML.
From JavaScript, grab the element and set checked.
This is the standard browser API. It works in every modern browser and requires no libraries.
Toggling a Checkbox
To flip the current state, negate the property.
This pattern is useful when a separate UI element controls the checkbox, such as a button or a keyboard shortcut handler.
Note that toggling through JavaScript does not fire the change event automatically. If your application relies on change listeners, you need to dispatch the event manually after toggling. More on that below.
Reacting to User Changes with the change Event
When a user clicks a checkbox, the browser fires a change event. Listen for it to run logic in response.
This is the standard pattern for forms, feature toggles, consent banners, and filter UIs. The change event fires only on user interaction by default. If you set checked programmatically and also need the event listener to run, dispatch the event yourself.
Working with Checkbox Groups
Real forms often contain groups of checkboxes. Query them together instead of handling each element individually.
Check all of them.
Uncheck all of them.
Collect the values of only the checked boxes.
The :checked pseudo-selector is powerful because it lets you query current state directly through querySelectorAll without looping and inspecting each element manually.
Select All / Deselect All Pattern
A "select all" checkbox that controls a group of child checkboxes is one of the most common UI patterns in admin dashboards, email clients, and bulk-action tables.
The second listener is the part developers forget. Without it, the "select all" checkbox stays checked even after a user unchecks an individual row, which breaks the visual contract.
Property vs. Attribute: Why setAttribute is Wrong
Developers sometimes try to check a checkbox like this.
This modifies the HTML attribute, not the DOM property. After a user interacts with the checkbox, the attribute and property diverge. The checked property tracks the live state. The attribute only reflects the initial value from markup.
| Approach | Controls | Tracks User Interaction |
checkbox.checked = true | DOM property | Yes |
checkbox.setAttribute('checked', '') | HTML attribute | No |
checkbox.removeAttribute('checked') | HTML attribute | No |
Always use the property for runtime behavior. The attribute is only relevant for the initial HTML render.
Form Validation with Checkboxes
A practical use case is requiring a terms-of-service checkbox before allowing form submission.
This reads the live checked property at the moment that matters most: right before the form submits.
Dynamically Rendered Checkboxes
When checkboxes are rendered dynamically (through client-side templates, API responses, or framework rendering), be careful about stale references. If you cache the result of querySelectorAll and then new checkboxes are added to the DOM, those new elements will not be in the cached NodeList.
Two solutions exist.
Re-query inside the event handler.
Or use event delegation on a parent container.
Event delegation is generally the better approach for dynamic content because it scales without re-binding listeners.
Common Pitfalls
Using setAttribute instead of the checked property. The attribute and property diverge after user interaction. Always use checkbox.checked for runtime state.
Reading the checkbox before it exists in the DOM. If your script runs in the <head> without defer or DOMContentLoaded, the element has not been created yet and getElementById returns null.
Forgetting that programmatic changes do not fire events. Setting checkbox.checked = true does not trigger change listeners. Dispatch the event manually if downstream logic depends on it.
Caching querySelectorAll results for dynamic lists. The returned NodeList is static. New elements added after the query will not appear in it. Re-query or use event delegation.
Over-engineering with JavaScript when HTML does the job. A <label> element natively toggles its associated checkbox. The required attribute enforces presence during form submission without any JavaScript. Reach for JS only when you need behavior beyond what HTML provides.
Summary
- Use
checkbox.checked = trueorfalseto check or uncheck a box. - Toggle with
checkbox.checked = !checkbox.checked. - Listen for the
changeevent to react to user interaction. - For groups, use
querySelectorAlland iterate over the results. - Prefer the live
checkedproperty over HTML attribute manipulation. - Dispatch
changeevents manually when toggling programmatically, if listeners depend on it. - Use event delegation for dynamically rendered checkbox lists.
Related reading
- Chess game in JavaScript
- Choosing between Thymeleaf and Angular for a new Spring MVC project
- Chrome Extensions synchronous calls - create window only after window
- Clearing localStorage in javascript?
- Client network socket disconnected before secure TLS connection was established. How can I connect to a kafka cluster using Kafka JS in Node js?
- Colors in JavaScript console
- Combine json arrays by key, javascript
- Compare Strings Javascript Return of Likely
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.