如何将复选框选择分成多个部分,并在每个部分上选择所有功能

问题描述 投票:0回答:2

我有超过 60 个客户需要使用复选框进行选择,我已经这样做了,这样我就可以选择单独的 1 个或多个客户,也可以选择所有功能来选择所有客户。

现在我想将这个客户选择分成3部分,每个部分都有全选功能,但我面临这样做的问题。这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Checkbox and Select All</title>
</head>
<body>
  <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>

    <script>
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);
});

  </script>
</body>
</html>

我做错了什么?

我试了很多次,都不会每部分都全选。我需要任何建议,请

javascript checkbox
2个回答
0
投票

如果您有多个具有相同逻辑的部分,我建议使用类名而不仅仅是 id。这将使选择它们变得更加容易。

您的代码中存在一些错误:

  1. sectionElement的选择器错误,它没有选择实际的section

     const sectionId = `customer-codes-section-${checkbox.id.split('-')[3]}`
     const sectionElement = document.getElementById(sectionId);
    
  2. customerCodeCheckboxes 选择器错误,它没有选择任何复选框。

    const customerCodeCheckboxes = document.querySelectorAll('.customer codes-section > li > input');
    
  3. 您将复选框设置为选中的逻辑是错误的。你有两个循环,彼此引用“复选框” - >避免这种情况

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

我的建议:始终确保您的选择器实际工作,通过记录它们的输出并查看它们是否返回正确的项目。

这是一个工作示例:https://jsfiddle.net/ah20oyrf/45/


0
投票

您的代码有一些问题:

  1. HTML 中没有任何以

    input
    :
     开头的 
    customer-code-section-

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

    应将其更新为仅选择带有

    customer-code
    的输入。我还将您从
    NodeList
    返回的
    querySelectorAll()
    包装在
    Array.from()
    中,以便您可以在
    .filter()
    事件侦听器中正确调用数组方法
    submitButton

    const customerCodeCheckboxes = Array.from(document.querySelectorAll('input[name="customer-code"]'));
    
  2. 您只需从

    "section"
    中抓取单词
    "select-all-section-N"
    并查找以
    section
    作为 id 的元素,但实际上没有:

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

    相反,您想要查找带有

    section-N
    作为
    id
    的元素,您可以使用
    .slice(2).join("-")
    来获取:

    const sectionCustomerCodeCheckboxes = sectionElement.querySelectorAll('input[type="checkbox"]');
    
  3. 您尝试在以下代码中使用不存在的变量 (

    selectAllCheckbox
    ):

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

    您真正想要做的是将当前迭代的复选框值设置为等于外部循环中的“所有”复选框值,为此,避免将内部

    checkbox
    变量调用为与外部循环中的变量相同的内容:

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

以下是这些变化:

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>

就个人而言,我会使用不同的方法,因为您的代码依赖于修补需要匹配其他

id
值的后缀的
id
名称。这可能会有点混乱。相反,我会向需要选择的元素添加
class
,并使用
.closest()
等方法来查找适当的部分,例如(详细信息请参阅代码注释):

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 psudo 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>

© www.soinside.com 2019 - 2024. All rights reserved.