Sometimes, we want to check if all checkboxes are unchecked with JavaScript.
In this article, we’ll look at how to check if all checkboxes are unchecked with JavaScript.
How to check if all checkboxes are unchecked with JavaScript?
To check if all checkboxes are unchecked with JavaScript, we can use the JavaScript array every
method.
For instance, we write:
<div>
<input type='checkbox' name='foo'>
<input type='checkbox' name='foo'>
</div>
to add 2 checkboxes.
Then we write:
const textinputs = document.querySelectorAll('input[type=checkbox]');
const empty = [...textinputs].every((el) => {
return !el.checked
});
console.log(empty)
We select the checkboxes with:
const textinputs = document.querySelectorAll('input[type=checkbox]');
Next, we spread the textInputs
into an array with the spread operator.
And then we call every
to check if all the checkboxes are unchecked by returning !el.checked
in the callback.
If all the checkboxes are unchecked, then empty
should be true
.
Conclusion
To check if all checkboxes are unchecked with JavaScript, we can use the JavaScript array every
method.