mardi 8 janvier 2019

check only direct childs when parent checkbox is checked

I want to check only child checkbox which does not have subchilds, when parent is checked.

I have created jsfiddle below, in which if we Check A1 only a2 should be checked. All other operation should be same.

$(function() {
    $('li :checkbox').on('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();
            console.log($ul)
            $parent = $ul.siblings(':checkbox');
            if ($chk.is(':checked')) {
                $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0)
            } else {
                $parent.prop('checked', false)
            }
            if($ul.get(0))
            if($ul.find(':checkbox:checked').length !== 0)
            $parent.prop('checked', true)          
            $chk = $parent;
            $li = $chk.closest('li');

        } while ($ul.is(':not(.someclass)'));
    });
});

JsFiddle




Aucun commentaire:

Enregistrer un commentaire