Home > Web Front-end > JS Tutorial > How to Create a 'Select All' Checkbox that Controls Other Checkboxes?

How to Create a 'Select All' Checkbox that Controls Other Checkboxes?

Mary-Kate Olsen
Release: 2024-11-09 09:07:02
Original
190 people have browsed it

How to Create a

How to Implement a Checkbox that Selects All Other Checkboxes

Implementing a "select all" checkbox in HTML allows you to easily toggle the selected state of multiple other checkboxes on the page.

Solution:

To achieve this functionality:

  1. Create a script tag with the following JavaScript code:
<script>
function toggle(source) {
  const checkboxes = document.getElementsByName('foo');
  for (let i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = source.checked;
  }
}
</script>
Copy after login
  1. In your HTML document, add the following code to create a "Select All" checkbox:
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br />
Copy after login
  1. Add the following code for your individual checkboxes:
<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 />
Copy after login

When you click the "Select All" checkbox, the script will loop through all checkboxes with the name "foo" and set their checked property to match the checked state of the "Select All" checkbox.

The above is the detailed content of How to Create a 'Select All' Checkbox that Controls Other Checkboxes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template