如何在嵌套复选框结构中选中父复选框时检查所有复选框?

问题描述:

大家好我有一个复杂的复选框结构,看起来像这样如何在嵌套复选框结构中选中父复选框时检查所有复选框?

<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应当检查,如果我检查一个由一个父所有子框中的复选框,父母框应该检查

和我有一个添加按钮在我的页面上单击添加按钮如果父类别被选中,并且该div的所有儿童都被检查我应该得到所有的价值我怎么能做到这一点可以帮助我解决这个问题或可以指导我通过这个

试试这个:Live Demo

// 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); 
    } 
}); 
+0

'.siblings'不走递归树倒不是吗?它只会检查......以及我的兄弟姐妹。我不相信的是作者的用例。 – Nucleon 2013-03-09 19:30:46

+0

@Nucleon是的,用'find'更新了答案。 – ATOzTOA 2013-03-09 19:41:56

+0

已更新答案... – ATOzTOA 2013-03-09 19:51:17

你可以这样做:

$('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); 
    } 
}); 

Demonstration