Home > Article > Web Front-end > How to Create a 'Select All' Checkbox that Controls Other Checkboxes?
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:
<script> function toggle(source) { const checkboxes = document.getElementsByName('foo'); for (let i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = source.checked; } } </script>
<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 />
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!