1

大家好,我有一个复杂的复选框结构,看起来像这样

<div class="accordian-group">
    <div>
    <input type="checkbox" class="parentcheckbox" value""/>
        <ul>
         <li> <input type="checkbox" value""/></li>
        <li> <input type="checkbox" value""/></li>
        <li> <input type="checkbox" value""/>
            <ul>
               <li> <input type="checkbox" value""/></li>
               <li> <input type="checkbox" value""/></li>
              <li> <input type="checkbox" value""/>
                    <ul>
                      <li> <input type="checkbox" value""/></li>
                    </u>
                </li>
           </ul>
       </li>
    </div>
     <div>
    <input type="checkbox" class="parentcheckbox" value""/>
        <ul>
         <li> <input type="checkbox" value""/></li>
        <li> <input type="checkbox" value""/></li>
        <li> <input type="checkbox" value""/>
            <ul>
               <li> <input type="checkbox" value""/></li>
               <li> <input type="checkbox" value""/></li>
              <li> <input type="checkbox" value""/>
                    <ul>
                      <li> <input type="checkbox" value""/></li>
                    </u>
                </li>
           </ul>
       </li>
    </div>
</div>

我要做的是检查父复选框时,应选中所有侧面的所有复选框,如果我一一检查所有的子盒子,请检查父复选框的所有内部子盒

如果父类别被选中并且该div的所有子项都被选中,我的页面中有一个添加按钮单击添加按钮引导我完成这个

4

2 回答 2

0

试试这个:现场演示

// Whenever the parent checkbox is checked/unchecked
$(".parentcheckbox").change(function() {
    // save state of parent
    c = $(this).is(':checked');
    $(this).parent().find("input[type=checkbox]").each(function() {
        // set state of siblings
        $(this).attr('checked', c);
    });
});

// Update parent checkbox based on children
$("input[type=checkbox]:not('.parentcheckbox')").change(function() {
    if ($(this).closest("div").find("input[type=checkbox]:not('.parentcheckbox')").not(':checked').length < 1) {
        $(this).closest("div").find(".parentcheckbox").attr('checked', true);
    } else {
        $(this).closest("div").find(".parentcheckbox").attr('checked', false);
    }
});
于 2013-03-09T19:28:35.867 回答
0

你可以这样做 :

 $('input[type="checkbox"]').change(function(){
  if (!$(this).is(':checked')) return; // do nothing if not checking
  var li = $(this).closest('li');

  // check all children 
  $('li input[type="checkbox"]', li).prop('checked', true);

  // see if all siblings are checked
  var all = true;
  li.siblings().find('>input[type="checkbox"]').each(function(){
    if (!$(this).is(':checked')) all = false;
  });
  if (all) {
    // check parent checkbox
    $(this).closest('ul').closest(':has(>input)')
          .find('input[type="checkbox"]').prop('checked', true);
  }
});

示范

于 2013-03-09T19:33:04.343 回答