Categories
JavaScript Answers

How to check if all checkboxes are unchecked with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *