I want to uncheck parent node if all children are unchecked.
<ul id="treeList">
<li>
<input type="checkbox" name="selectedRole">
Application Manager
<ul>
<li>
<input type="checkbox" name="selectedRole">
Application Manager Panel
</li>
<li>
<input type="checkbox" name="selectedRole">
Client Role
<ul>
<li>
<input type="checkbox" name="selectedRole">
Client Task 1
</li>
开发者_如何学C <li>
<input type="checkbox" name="selectedRole">
Client Task 2
</li>
</ul>
</li>
</ul>
</li>
I have following jQuery script. But when I uncheck any children, the parent got uncheck. It should see, if all children are unchecked. then it should uncheck the parent.
jQuery.each(jQuery('#treeList ul li').find(':checkbox'), function(){
jQuery(this).change(function (){
if (jQuery(this).is(':checked')) {
jQuery(this).parents('ul').siblings('input:checkbox').attr('checked', true);
}else{
jQuery(this).parents('ul').siblings('input:checkbox').attr('checked', false);
}
});
});
You are unchecking the parent li
checkbox every time you uncheck a child, instead of checking if there's still some other checked items. Instead, you could check the number of items checked
and use that length
as a boolean
:
jQuery.each(jQuery('#treeList ul li').find(':checkbox'), function(){
jQuery(this).change(function (){
if (jQuery(this).is(':checked')) {
jQuery(this).parentsUntil('#treeList').siblings().filter('input:checkbox').attr('checked', true).trigger('change');
}else{
jQuery(this).parents('ul:first').siblings('input:checkbox').prop('checked', $(this).parent().siblings().children('input:checked').length).trigger('change');
}
});
});
example: http://jsfiddle.net/niklasvh/fRxVs/
Here is your fiddle's updated version... added some CSS to clarify the Tree Level (Parent and Child Relationship ) http://jsfiddle.net/vimalpatel/fRxVs/440/
Here you have:
$("#treeList :checkbox").change(function(){
uncheckParentIfSiblingsUnchecked($(this));
});
function uncheckParentIfSiblingsUnchecked($chk){
if($chk.size() == 1 && !$chk.is(":checked")){
$checked_siblings = $chk.closest("ul").children("li").children(":checkbox:checked");
if($checked_siblings.size() == 0){
$parent_checkbox = $chk.closest("ul").prev(":checkbox").attr("checked", false);
uncheckParentIfSiblingsUnchecked($parent_checkbox);
}
}
}
It's recursive cause it must 'bubble' to the root checkbox. Hope this helps. Cheers
精彩评论