复选框全部点击 [英] Check boxes clicked all

查看:100
本文介绍了复选框全部点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在点击任何一个孩子时选择父项。此代码正在检查并检查。

I want to select the parent item when any of the child is clicked. This code is working checked and check.

$(function() {
  $(".child").on("click",function() {
      $parent = $(this).prevAll(".parent");
      if ($(this).is(":checked")) $parent.prop("checked",true);
      else {
         var len = $(this).parent().find(".child:checked").length;
         $parent.prop("checked",len>0);
      }    
  });
  $(".parent").on("click",function() {
      $(this).parent().find(".child").prop("checked",this.checked);
  });
});

它正在使用输入(参见链接

It's working with inputs (See this link)

<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 2

但是< li>检查无效(请参阅此链接

But with < li > check is not working (See this link)

<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1
<ul>
    <il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 1</il>
    <il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 2</il>
</ul>    


推荐答案

看完你的代码后,我想出了我认为你想要的解决方案。

after looking at your code, i have come up with a solution that i think you're going for.

通过使用自定义属性,我选择了顶级复选框,如果选中了其中一​​个子复选框。如果选中至少一个子级别复选框,则父级别保持选中状态。否则,未经检查。这可能比导航DOM更容易,最终代码更少。

by using custom attributes, i selected the top level checkbox if one of the child checkboxes is selected. if at least one child level checkbox is checked, the parent level stays checked. otherwise, unchecked. this is probably easier than navigating the DOM and ended up being much less code.

$(function() {
  $(".child").change(function() {
      if ($('.child[thisparent=' + $(this).attr('thisparent') + ']:checked').length == 0) {
          $('#' + $(this).attr('thisparent')).prop('checked', false);
      }
      else {
          $('#' + $(this).attr('thisparent')).prop('checked', true);
      }
  });
  $(".parent").change(function() {
      $('input[thisparent="' + $(this).attr('id') + '"]').prop('checked', $(this).prop('checked'));
  });
});

JSFiddle:此处

JSFiddle: here

此外,您的HTML无效。你的il标签应该是li

also, your html is invalid. your "il" tags should be "li"

这篇关于复选框全部点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆