Check/Uncheck Parent/Child Checkboxes using Jquery

2019-04-14 05:20发布

问题:

I am not really that familiar with jquery or javascript and I need a quick solution to my problem that is why im posting it here. Below is a sample html snippet:

<ul>
<li><input type="checkbox" />Administration
    <ul>
        <li><input type="checkbox" />President
            <ul>
                <li><input type="checkbox" />Manager 1
                    <ul>
                        <li><input type="checkbox" />Assistant Manager 1</li>
                        <li><input type="checkbox" />Assistant Manager 2</li>
                        <li><input type="checkbox" />Assistant Manager 3</li>
                    </ul>
                </li>
                <li><input type="checkbox" />Manager 2</li>
                <li><input type="checkbox" />Manager 3</li>
            </ul>
        </li>
        <li><input type="checkbox" />Vice President
            <ul>
                <li><input type="checkbox" />Manager 4</li>
                <li><input type="checkbox" />Manager 5</li>
                <li><input type="checkbox" />Manager 6</li>
            </ul>
        </li>
    </ul>
</li>
</ul>

What I would like to do is to check everything when Administration is checked. If I uncheck President, then, his parent/s should be unchecked also together with his children leaving only the Vice President and his children checked. Similarly, if I check Manager 1 then his children should be checked also. But if I uncheck Assistant Manager 1 then Manager 1 should also be unchecked leaving only Asst. Manager 2 and 3 checked.

Take note that this list is dynamic. Meaning a child can have more children and so on.

Thanks in advance!

回答1:

See this: DEMO

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

Courtesy: Uncheck parent checkbox if one child is unchecked