JavaScript - Select or deselect all checkboxes
A simple code example introducing how to select or deselect all checkboxes at once in JavaScript.
The HTML has multiple checkboxes with class "checkbox". It also has buttons to select all or deselect all.
<div class="item-container">
<button type="button" id="all-true">Select All</button>
<button type="button" id="all-false">Deselect All</button>
<div class="checkboxs">
<p><input type="checkbox" id="checkbox-a" class="checkbox" name="name" value="A">
<label for="checkbox-a">A</label></p>
<p><input type="checkbox" id="checkbox-b" class="checkbox" name="name" value="B">
<label for="checkbox-b">B</label></p>
<p><input type="checkbox" id="checkbox-c" class="checkbox" name="name" value="C">
<label for="checkbox-c">C</label></p>
</div>
</div>
The target checkboxes are queried together with querySelectorAll()
.
When the select all or deselect all buttons are pressed and execute their events, the checkboxes are iterated and selected/deselected using a for loop.
// Get all target checkboxes
let checkboxs = document.querySelectorAll('.checkbox');
// Select all button event
document.querySelector('#all-true').addEventListener('click', () => {
for (const check of checkboxs) {
check.checked = true;
}
});
// Deselect all button event
document.querySelector('#all-false').addEventListener('click', () => {
for (const check of checkboxs) {
check.checked = false;
}
});