Sometimes, we want to implement select all check box in HTML and JavaScript.
In this article, we’ll look at how to implement select all check box in HTML and JavaScript.
How to implement select all check box in HTML and JavaScript?
To implement select all check box in HTML and JavaScript, we set the checked
value of each checkbox.
For instance, we write
<input type="checkbox" id="check-all" />Check all?<br />
<input type="checkbox" />Bar 1<br />
<input type="checkbox" />Bar 2<br />
<input type="checkbox" />Bar 3<br />
<input type="checkbox" />Bar 4<br />
to add checkboxes.
Then we write
const source = document.querySelector("#check-all");
source.onclick = () => {
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (const checkbox of checkboxes) {
if (checkbox !== source) {
checkbox.checked = source.checked;
}
}
};
to select the check all checkbox with document.querySelector("#check-all");
.
Then we set its onclick
property to a function that’s called when we click on it.
In it, we select all the checkboxes with querySelectorAll
.
And then we loop through each checkbox with a for-of loop.
In the loop, we check if the checkbox
is the same as the source
one.
If it’s not, then we get the checked value of source
and set it as the checked value of checkbox
.
Conclusion
To implement select all check box in HTML and JavaScript, we set the checked
value of each checkbox.