How to implement "select all" check box in HTML?

javascript

To implement a “select all” checkbox in HTML, you can use JavaScript to toggle the checked state of all the checkboxes in a group when the “select all” checkbox is clicked. Here is an example implementation:

<label for="select-all-checkbox">Select All:</label>
<input type="checkbox" id="select-all-checkbox" onclick="toggleCheckboxes()">

<label for="checkbox1">Checkbox 1</label>
<input type="checkbox" id="checkbox1">

<label for="checkbox2">Checkbox 2</label>
<input type="checkbox" id="checkbox2">

<label for="checkbox3">Checkbox 3</label>
<input type="checkbox" id="checkbox3">

<script>
function toggleCheckboxes() {
  // Get all the checkboxes
  var checkboxes = document.querySelectorAll('input[type="checkbox"]');

  // Toggle the checked state of all the checkboxes
  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = document.getElementById('select-all-checkbox').checked;
  }
}
</script>

In this example, we first create a “select all” checkbox with an id of select-all-checkbox. We also create some checkboxes with unique id attributes.

We then add an onclick event listener to the “select all” checkbox that calls the toggleCheckboxes() function. The toggleCheckboxes() function gets all the checkboxes on the page using document.querySelectorAll(‘input[type=“checkbox”]’), and toggles the checked state of each checkbox based on the checked state of the “select all” checkbox.

When the “select all” checkbox is checked, all the checkboxes on the page will be checked. When the “select all” checkbox is unchecked, all the checkboxes on the page will be unchecked.

You can modify the toggleCheckboxes() function to only toggle the checked state of specific checkboxes, or to perform additional actions when a checkbox is checked or unchecked.