如果未选中一个子项,请取消选中父复选框 [英] Uncheck parent checkbox if one child is unchecked

查看:157
本文介绍了如果未选中一个子项,请取消选中父复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要多个复选框的值的应用程序。我有嵌套列表包含复选框。目前的功能是:


  1. 选择父项时,会检查所有子项。

  2. <

    我需要添加此功能:



  3. 如果在选中父项后未选中子项,父项将取消选中,但会将子项选中。



    $('input [name =level-1],input [name =level-2]' $ b $('input [type = checkbox]',$(this).parent('li'))。attr('checked',($(this).is(':checked')));
    });


我的代码在这里:

一种可能的解决方案



添加一个类 someclass c $ c> ul 元素然后

  $('。someclass:checkbox')。bind 'click',function(){
var $ chk = $(this),$ li = $ chk.closest('li'),$ ul,
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)')。 = 0)
} else {
$ parent.prop('checked',false)
}
$ chk = $ parent;
$ li = $ chk.closest('li');
} while($ ul.is(':not(.someclass)'));
});

演示:小提琴


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/

解决方案

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

这篇关于如果未选中一个子项,请取消选中父复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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