Uncheck parent checkbox if one child is unchecked

泪湿孤枕 提交于 2019-12-30 11:15:20

问题


I am developing an application that requires the value of multiple checkboxes. I have nested lists containing checkboxes. The current functionality is this:

  1. When a parent is checked, all children are checked under it.
  2. When a child is checked, the parent is not selected.

I need to add this functionality:

  1. When a child is unchecked after the parent is checked, the parent unchecks, but leaves the children checked.

    $('input[name="level-1"],input[name="level-2"]').bind('click', function () { $('input[type=checkbox]', $(this).parent('li')).attr('checked', ($(this).is(':checked'))); });

My code is found here: http://jsfiddle.net/dbcottam/Py4UN/


回答1:


A possible solution

Add a class someclass to the topmost ul element then

$('.someclass :checkbox').bind('click', function () {
    var $chk = $(this), $li = $chk.closest('li'), $ul, $parent ;
    if($li.has('ul')){
        $li.find(':checkbox').not(this).prop('checked', this.checked)
    }

    do{
        $ul = $li.parent();
        $parent = $ul.siblings(':checkbox');
        if($chk.is(':checked')){
            $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
        } else {
            $parent.prop('checked', false)
        }
        $chk = $parent;
        $li = $chk.closest('li');
    } while($ul.is(':not(.someclass)'));
});

Demo: Fiddle




回答2:


I tried out a generic function to handle multiple levels. See code below,

$('input[name^="level"]').click(function () {
    //v-- Takes care of check/uncheck all child checkbox
    $(this).parent().find('input[name^=level]').prop('checked', this.checked);

    if (!this.checked) {
        var level = this.name.substring(this.name.length - 1);    
        //using the naming convention `level-n` to uncheck parent
        for (var i = level - 1; i > 0; i--) {
            $('input[name="level-' + i + '"]').prop('checked', false);
        }
    }
});

DEMO: http://jsfiddle.net/46hTc/



来源:https://stackoverflow.com/questions/18233624/uncheck-parent-checkbox-if-one-child-is-unchecked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!