【问题标题】:Programatically checking all checkbox doesn't work properly when any of the target checkboxes checked / unchecked manually当手动选中/取消选中任何目标复选框时,以编程方式检查所有复选框无法正常工作
【发布时间】:2018-01-19 06:41:14
【问题描述】:

当手动选中/取消选中任何目标复选框时,以编程方式检查所有复选框无法正常工作 我有两种方法,一种是选中所有复选框,另一种是取消选中所有复选框值

我将它们命名为 selectAll 和 unSelectall。当 selectAll 被触发时,它会检查所有的复选框,但是当 unSelectall 被触发时,它会取消选中所有的复选框,但是当您选中/取消选中任何目标复选框然后单击 checkall 或取消选中全部时,问题是什么,手动选中/ 未选中的复选框不起作用。这是fiddle上的工作代码

function selectAll() {
    const checkboxes = document.querySelectorAll('.myCheck');
    let i = 0;
    while(i < checkboxes.length) {
      checkboxes[i].setAttribute("checked", "checked");
      i++;
    }
  }
  function unSelectAll() {  
    const checkboxes = document.querySelectorAll('.myCheck');
    let i = 0;
    while(i < checkboxes.length) {
      checkboxes[i].removeAttribute("checked", "");
      i++;
    }
  }

【问题讨论】:

  • 按照@gurvinder372的建议,您应该使用.checked。但是您不需要 2 个功能。您可以创建一个函数,将true 用于选择,false 用于取消选择并相应地进行处理。 Updated Fiddle。此外,元素的id 应该是唯一的。

标签: javascript ecmascript-6


【解决方案1】:

不要使用setAttributeremoveAttribute,而是直接使用checked 属性

  function selectAll() {
    const checkboxes = document.querySelectorAll('.myCheck');
    let i = 0;
    while (i < checkboxes.length) {
      checkboxes[i].checked = true;
      i++;
    }
  }

  function unSelectAll() {
    const checkboxes = document.querySelectorAll('.myCheck');
    let i = 0;
    while (i < checkboxes.length) {
      checkboxes[i].checked = false;
      i++;
    }
  }

演示

<!DOCTYPE html>
<html>

  <body>

    All:
    <input onclick="selectAll();" type="checkbox" id="all"> uncheckAll:
    <input onclick="unSelectAll();" type="checkbox" id="all">
    <br/> ckbx1:
    <input type="checkbox" class="myCheck"> ckbx2:
    <input type="checkbox" class="myCheck"> ckbx3:
    <input type="checkbox" class="myCheck"> ckbx4:
    <input type="checkbox" class="myCheck">

    <p>checl all and uncheck all</p>

    <script>
      function selectAll() {
        const checkboxes = document.querySelectorAll('.myCheck');
        let i = 0;
        while (i < checkboxes.length) {
          checkboxes[i].checked = true;
          i++;
        }
      }

      function unSelectAll() {
        const checkboxes = document.querySelectorAll('.myCheck');
        let i = 0;
        while (i < checkboxes.length) {
          checkboxes[i].checked = false;
          i++;
        }
      }

    </script>

  </body>

</html>

【讨论】:

  • 也许你需要添加一个检查只有当alluncheckAll被选中时,你必须继续。考虑以下情况: 1. 选择全选。 2. 选择取消调用。 (现在除了 checkall 和 uncheckall 框外,什么都不会被选中)。 3. 现在取消选中复选框。 (所有复选框都会被选中。由于无论选中框的状态如何都会触发 onclick,因此它会执行操作)
  • @VigneshRaja 这是用户体验的一部分,不在讨论范围内。我同意这一点,但问题只是关于 select/unselect all。让我们不要过度设计它。
  • .checked = true;产生打字稿错误“类型元素上不存在已检查的属性”
  • @karty 打字稿?打字稿不是您最初问题的一部分。你能分享一个重现错误的小提琴吗?
  • 我知道这是一个类型错误。感谢您花费宝贵的时间来回答我的问题。接受你的回答。支持我的问题将不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2021-09-04
相关资源
最近更新 更多