skip to Main Content

I have more than 60 customer need to select using checkbox, I have done this so I can select individual 1 or more customer and also select all function to select all the customers.

Now I want to to break this customer selection into 3 parts, every part has the select all function, but I am facing a problem with doing that. Here is my code:

const selectAllCheckboxes = document.querySelectorAll('input[id^="select-all-section-"]');
const customerCodeCheckboxes = document.querySelectorAll('input[name^="customer-code-section-"]');
const submitButton = document.querySelector('#submit-button');

// Add a click event listener to each select all checkbox
selectAllCheckboxes.forEach(checkbox => {
  checkbox.addEventListener('click', () => {
    // Get the corresponding section element
    const sectionElement = document.querySelector(`#${checkbox.id.split('-')[2]}`);

    // Get all of the customer code checkboxes in the section
    const sectionCustomerCodeCheckboxes = sectionElement.querySelectorAll('input[type="checkbox"]');

    // Select or deselect all of the customer code checkboxes in the section, depending on the state of the select all checkbox
    sectionCustomerCodeCheckboxes.forEach(checkbox => {
      checkbox.checked = selectAllCheckbox.checked;
    });
  });
});

// Add a click event listener to the submit button
submitButton.addEventListener('click', () => {
  // Get the selected customer code IDs
  const selectedCustomerCodeIds = customerCodeCheckboxes.filter(checkbox => checkbox.checked).map(checkbox => checkbox.value);

  // Log the selected customer code IDs to the console
  console.log('Selected customer code IDs:', selectedCustomerCodeIds);
});
<h1>Checkbox and Select All</h1>

<div id="section-1">
  <h2>Section 1</h2>
  <input type="checkbox" id="select-all-section-1">
  <label for="select-all-section-1">Select All</label>
  <ul id="customer-codes-section-1">
    <li><input type="checkbox" name="customer-code" value="HAN01">HAN01</li>
    <li><input type="checkbox" name="customer-code" value="HAN02">HAN02</li>
    <li><input type="checkbox" name="customer-code" value="HAN03">HAN03</li>
    <li><input type="checkbox" name="customer-code" value="HAN04">HAN04</li>
  </ul>
</div>

<div id="section-2">
  <h2>Section 2</h2>
  <input type="checkbox" id="select-all-section-2">
  <label for="select-all-section-2">Select All</label>
  <ul id="customer-codes-section-2">
    <li><input type="checkbox" name="customer-code" value="ABC01">ABC01</li>
    <li><input type="checkbox" name="customer-code" value="ABC02">ABC02</li>
    <li><input type="checkbox" name="customer-code" value="ABC03">ABC03</li>
    <li><input type="checkbox" name="customer-code" value="ABC04">ABC04</li>
    <li><input type="checkbox" name="customer-code" value="ABC05">ABC05</li>
  </ul>
</div>

<button type="button" id="submit-button">Submit</button>

What am I doing wrong?

I tried many times, and it wont select all in every part. I need any suggestion please

2

Answers


  1. If you have multiple sections with the same logic i would recommend using a classname instead of just ids. This will make selecting them much easier.

    There were some errors in your code:

    1. The selector of the sectionElement was wrong, it did’t select the actual section

       const sectionId = `customer-codes-section-${checkbox.id.split('-')[3]}`
       const sectionElement = document.getElementById(sectionId);
      
    2. The customerCodeCheckboxes selector was wrong it was not selecting any checkboxes.

      const customerCodeCheckboxes = document.querySelectorAll('.customer codes-section > li > input');
      
    3. The logic were you set you checkboxes to checked was wrong. You had two loops with references on "checkbox" within each other -> avoid this

      selectAllCheckboxes.forEach(checkbox => {
       checkbox.addEventListener('click', () => {
       [...]
       sectionCustomerCodeCheckboxes.forEach(customerCheckbox => {
         customerCheckbox.checked = checkbox.checked;
       });
      });
      

    My Advice: always make sure your selectors actually work, by logging their outputs and see if they return the correct items.

    Here is a working example: https://jsfiddle.net/ah20oyrf/45/

    Login or Signup to reply.
  2. Your code has a few issues:

    1. Nowhere in your HTML do you have any input elements that start with the customer-code-section-:

      const customerCodeCheckboxes = document.querySelectorAll('input[name^="customer-code-section-"]');
      

      This should be updated to select just inputs with customer-code. I’m also wrapping the NodeList that you get back from querySelectorAll() in Array.from() so that you can correctly call the array method .filter() in your submitButton event listener:

      const customerCodeCheckboxes = Array.from(document.querySelectorAll('input[name="customer-code"]'));
      
    2. In the below code you’re just grabbing the word "section" from the checkbox id of "select-all-section-N" and then looking for elements with section as the id, which there are none:

      const sectionElement = document.querySelector(`#${checkbox.id.split('-')[2]}`);
      

      Instead, it seems you want to look for elements with section-N as the id, which you can grab using .slice(2).join("-") instead (see slice() & join() docs for more info):

      const sectionCustomerCodeCheckboxes = sectionElement.querySelectorAll('input[type="checkbox"]');
      
    3. You’re trying to use a variable that doesn’t exist (selectAllCheckbox) in the following code:

      sectionCustomerCodeCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
      });
      

      What you really want to do here is set the currently iterated checkbox value equal to the "all" checkbox value from the outer loop that surrounds this portion of code, to do this, avoid giving your inner checkbox variable the same name as the one in the outer loop, this way you won’t "shadow" the outer variable:

      // different name from outer variable ---v
      sectionCustomerCodeCheckboxes.forEach(selectionCheckbox => {
        selectionCheckbox.checked = checkbox.checked;
      });
      

    Below is a working example with these changes implemented (expand to see runnable example):

    const selectAllCheckboxes = document.querySelectorAll('input[id^="select-all-section-"]');
    const customerCodeCheckboxes = Array.from(document.querySelectorAll('input[name="customer-code"]'));
    const submitButton = document.querySelector('#submit-button');
    
    // Add a click event listener to each select all checkbox
    selectAllCheckboxes.forEach(checkbox => {
      checkbox.addEventListener('click', () => {
        // Get the corresponding section element
        const sectionElement = document.querySelector(`#${checkbox.id.split('-').slice(2).join("-")}`);
    
        // Get all of the customer code checkboxes in the section
        const sectionCustomerCodeCheckboxes = sectionElement.querySelectorAll('input[type="checkbox"]');
    
        // Select or deselect all of the customer code checkboxes in the section, depending on the state of the select all checkbox
        sectionCustomerCodeCheckboxes.forEach(selectionCheckbox => {
          selectionCheckbox.checked = checkbox.checked;
        });
      });
    });
    
    // Add a click event listener to the submit button
    submitButton.addEventListener('click', () => {
      // Get the selected customer code IDs
      const selectedCustomerCodeIds = customerCodeCheckboxes.filter(checkbox => checkbox.checked).map(checkbox => checkbox.value);
    
      // Log the selected customer code IDs to the console
      console.log('Selected customer code IDs:', selectedCustomerCodeIds);
    });
    <h1>Checkbox and Select All</h1>
    
    <div id="section-1">
      <h2>Section 1</h2>
      <input type="checkbox" id="select-all-section-1">
      <label for="select-all-section-1">Select All</label>
      <ul id="customer-codes-section-1">
        <li><input type="checkbox" name="customer-code" value="HAN01">HAN01</li>
        <li><input type="checkbox" name="customer-code" value="HAN02">HAN02</li>
        <li><input type="checkbox" name="customer-code" value="HAN03">HAN03</li>
        <li><input type="checkbox" name="customer-code" value="HAN04">HAN04</li>
      </ul>
    </div>
    
    <div id="section-2">
      <h2>Section 2</h2>
      <input type="checkbox" id="select-all-section-2">
      <label for="select-all-section-2">Select All</label>
      <ul id="customer-codes-section-2">
        <li><input type="checkbox" name="customer-code" value="ABC01">ABC01</li>
        <li><input type="checkbox" name="customer-code" value="ABC02">ABC02</li>
        <li><input type="checkbox" name="customer-code" value="ABC03">ABC03</li>
        <li><input type="checkbox" name="customer-code" value="ABC04">ABC04</li>
        <li><input type="checkbox" name="customer-code" value="ABC05">ABC05</li>
      </ul>
    </div>
    
    <button type="button" id="submit-button">Submit</button>

    Personally, I would use a different approach as your code relies on tinkering with id names that need to match suffixes of other id values. This can get a bit messy. Instead, I would add a class to the elements that need to be selected, and use methods such as .closest() to find the corresponding section the clicked "select-all" checkbox is in, as well as the :checked pseudo-class to get your final checked checkbox values, for example (see code comments for details):

    const selectAllCheckboxes = document.querySelectorAll('.select-all');
    const customerCodeCheckboxes = document.querySelectorAll('.code-cb');
    const submitButton = document.querySelector('#submit-button');
    
    // Add a click event listener to each select all checkbox (fine if there aren't too many sections, use event-delegation instead if you have many)
    selectAllCheckboxes.forEach(checkbox => {
      checkbox.addEventListener('click', () => {
        // Get the corresponding section element
        const sectionElement = checkbox.closest(".section"); // find parent element with the class of section
    
        // Get all of the customer code checkboxes in the section
        const sectionCustomerCodeCheckboxes = sectionElement.querySelectorAll('.code-cb');
    
        // Select or deselect all of the customer code checkboxes in the section, depending on the state of the select all checkbox
        sectionCustomerCodeCheckboxes.forEach(selectionCheckbox => {
          selectionCheckbox.checked = checkbox.checked;
        });
      });
    });
    
    // Add a click event listener to the submit button
    submitButton.addEventListener('click', () => {
      // Get the selected customer code IDs
      const checkedCheckboxes = document.querySelectorAll(".code-cb:checked"); // use the pseudo-class selector of `:checked` to only select checked checkboxes
      const selectedCustomerCodeIds = Array.from(checkedCheckboxes, checkbox => checkbox.value);
    
      // Log the selected customer code IDs to the console
      console.log('Selected customer code IDs:', selectedCustomerCodeIds);
    });
    <h1>Checkbox and Select All</h1>
    
    <div class="section" id="section-1">
      <h2>Section 1</h2>
      <input type="checkbox" id="select-all-section-1" class="select-all">
      <label for="select-all-section-1">Select All</label>
      <ul id="customer-codes-section-1">
        <li><input type="checkbox" class="code-cb" name="customer-code" value="HAN01">HAN01</li>
        <li><input type="checkbox" class="code-cb" name="customer-code" value="HAN02">HAN02</li>
        <li><input type="checkbox" class="code-cb" name="customer-code" value="HAN03">HAN03</li>
        <li><input type="checkbox" class="code-cb" name="customer-code" value="HAN04">HAN04</li>
      </ul>
    </div>
    
    <div class="section" id="section-2">
      <h2>Section 2</h2>
      <input type="checkbox" id="select-all-section-2" class="select-all">
      <label for="select-all-section-2">Select All</label>
      <ul id="customer-codes-section-2">
        <li><input type="checkbox" class="code-cb" name="customer-code" value="ABC01">ABC01</li>
        <li><input type="checkbox" class="code-cb" name="customer-code" value="ABC02">ABC02</li>
        <li><input type="checkbox" class="code-cb" name="customer-code" value="ABC03">ABC03</li>
        <li><input type="checkbox" class="code-cb" name="customer-code" value="ABC04">ABC04</li>
        <li><input type="checkbox" class="code-cb" name="customer-code" value="ABC05">ABC05</li>
      </ul>
    </div>
    
    <button type="button" id="submit-button">Submit</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search