Categories
JavaScript Answers

How to implement “select all” check box with JavaScript?

Spread the love

To implement "select all" check box with JavaScript, we can loop through all the checkboxes and check them.

For instance, we write

<input type="checkbox" onclick="toggle(this)" /> Toggle All<br />

<input type="checkbox" name="foo" value="bar1" /> Bar 1<br />
<input type="checkbox" name="foo" value="bar2" /> Bar 2<br />
<input type="checkbox" name="foo" value="bar3" /> Bar 3<br />
<input type="checkbox" name="foo" value="bar4" /> Bar 4<br />

to add some checkboxes.

We set the onclick attribute of the first checkbox to call toggle with the checkbox as its argument.

Then we write

function toggle(source) {
  const checkboxes = document.getElementsByName("foo");
  for (const checkbox of checkboxes) {
    checkbox.checked = source.checked;
  }
}

to define the toggle function.

In it, we get all the checkboxes with name attribute foo with getElementsByName.

And then we loop through each one with a for-of loop.

In it, we set the checked value of the checkbox to checked value of the first checkbox.

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 *