JavaScript : Checkbox Selector – Check and Uncheck Multiple Checkboxes using JavaScript

Java Script @ Freshers.in

This HTML page demonstrates how to create a checkbox selector that allows users to check or uncheck multiple checkboxes with a single checkbox. The “Select All” checkbox at the top of the list can be used to toggle the state of all the checkboxes below. This feature provides a convenient way to manage the selection status of multiple checkboxes at once. The code utilizes JavaScript to handle the checkbox selection logic and ensures that the state of the checkboxes stays synchronized with the “Select All” checkbox.

Here’s a complete HTML code that includes five checkboxes and a “Select All” checkbox that can be used to check or uncheck all the checkboxes:
<!DOCTYPE html>
<html>
<head>
  <title>Checkbox Example</title>
  <style>
    label {
      display: block;
    }
  </style>
</head>
<body>
  <h1>Checkbox Example</h1>
  
  <label>
    <input type="checkbox" id="selectAllCheckbox" onchange="selectAll()"> Select All
  </label>
  
  <hr>
  
  <label>
    <input type="checkbox" class="checkbox"> Checkbox 1
  </label>
  
  <label>
    <input type="checkbox" class="checkbox"> Checkbox 2
  </label>
  
  <label>
    <input type="checkbox" class="checkbox"> Checkbox 3
  </label>
  
  <label>
    <input type="checkbox" class="checkbox"> Checkbox 4
  </label>
  
  <label>
    <input type="checkbox" class="checkbox"> Checkbox 5
  </label>
  
  <script>
    function selectAll() {
      const selectAllCheckbox = document.getElementById('selectAllCheckbox');
      const checkboxes = document.querySelectorAll('.checkbox');

      checkboxes.forEach((checkbox) => {
        checkbox.checked = selectAllCheckbox.checked;
      });
    }
  </script>
</body>
</html>

Let’s break down the code and understand each part:

  1. The <style> block includes a simple CSS rule to display each checkbox label on a new line for better readability.
  2. The <label> element contains the “Select All” checkbox. It has an id attribute of “selectAllCheckbox” and an onchange event listener that triggers the selectAll() function when its value changes.
  3. After the <hr> element, there are five checkboxes labeled “Checkbox 1” to “Checkbox 5”. Each checkbox has a class attribute set to “checkbox” for easy selection in JavaScript.
  4. The <script> block contains the selectAll() function. When the “Select All” checkbox is checked or unchecked, this function is called. It selects all checkboxes on the page using document.querySelectorAll(‘.checkbox’) and then sets their checked property to the value of the “Select All” checkbox.
Author: user

Leave a Reply