【问题标题】:Parent/child checkboxes with label带标签的父/子复选框
【发布时间】:2020-05-11 18:02:12
【问题描述】:

我希望父母/复选框具有这种行为:

  1. 单击父级选择/取消选择所有子级
  2. 如果选择了一个或多个孩子,则会检查父母
  3. 如果没有选择子项,则取消选中父项

该代码有效:

<ul class="list-group" id="mydiv">
   <li class="list-group-item"><input type="checkbox" name="parent1" id="parent1" value=""> <label for "parent1">Parent 1</label>
      <ul class="list-group">
         <li class="list-group-item"><input type="checkbox" name="child11" value=""> Child 11</li>
         <li class="list-group-item"><input type="checkbox" name="child12" value=""> Child 12</li>
         <li class="list-group-item"><input type="checkbox" name="child13" value=""> Child 31</li>
      </ul>
   </li>

   <li class="list-group-item"><input type="checkbox" name="parent2" value=""> Parent 2
      <ul class="list-group">
         <li class="list-group-item"><input type="checkbox" name="child21" value=""> Child 21</li>
         <li class="list-group-item"><input type="checkbox" name="child22" value=""> Child 22</li>
      </ul>
   </li>
</ul>

JS:

$('input[type=checkbox]').click(function(){
   $(this).next().find('input[type=checkbox]').prop('checked',this.checked);
   $(this).parents('ul').prev('input[type=checkbox]').prop('checked',function(){
      return $(this).next().find(':checked').length;
   });
});

我担心的是,一旦我设置了

这是笔:https://codepen.io/Jibeji/pen/povYKXo

【问题讨论】:

  • 如果在检查其中一个子项时检查父项(顺便说一句,在 &lt;input&gt; 等 void 元素之间实际上并不存在父/子关系),这可能会让用户感到困惑。假设一个孩子被检查然后父母也被检查......这意味着父母可以产生3个状态但只有2个指示:1。未选中父级: 所有子级均未选中,2。已检查父级: 检查所有子级,3。已检查父级: 检查了一些子级?
  • 我理解你的意思,但这是我需要的行为。

标签: javascript jquery checkbox


【解决方案1】:

回答我自己。这更优雅并且支持标签:

$('input[type=checkbox]').click(function(){
   $(this).nextUntil('li').find('input[type=checkbox]').prop('checked',this.checked);
   $(this).closest('ul').siblings('input:checkbox').prop('checked',function(){
      return $(this).nextUntil('li').find(':checked').length;
   });
});

原始笔已编辑。

【讨论】:

    【解决方案2】:

    它不再起作用,因为$(this).next() 不再引用下一个输入,因为那里有标签。看来你想要.next().next()。不过,您可能需要一种不同的方式来选择 ul,因为您可以看到这种设置很容易被破坏。

    【讨论】:

    • 感谢 Tenor528 的信息。您对更强大的脚本有什么建议吗?这些复选框是动态生成的,数量可以改变,这就是我寻找通用解决方案的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2014-05-01
    相关资源
    最近更新 更多