74H1R
74H1R

Reputation: 3514

Checking all immediate parent checkboxes in JQuery

I have this nested list structure. My tree can go to n level.

I want a selector of JQuery that can only select the parents, if child is checked.

<ul id="treeFeatureList">
<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>
                <li>
                    <input type="checkbox" name="selectedRole">
                    Client Task 2
                </li>
            </ul>
        </li>
    </ul>
</li>
</ul>

What I want: If client Task1 or Task2 is checked, the Client Role and Application Manager got checked too. Definitely not Application Manager Panel (that should remain unchecked).

Help is appreciated to make this magical selector.

Upvotes: 0

Views: 2408

Answers (3)

user2117220
user2117220

Reputation: 1

$('input[type="checkbox"]').change(function() {
if ($(this).is(':checked')) {
    $(this).parents('ul').siblings('input:checkbox').attr('checked', true);
} else {
        //if any of the sibling is checked, do not  uncheck the main category
        var isSiblingChecked = false;
        $(this).parent().siblings().each(function() {
            if (($(this).find('input[type="checkbox"]').is(':checked'))) {
                isSiblingChecked = true;
            }
        });     
        if (isSiblingChecked == false) {            
    $(this).parents('ul').siblings('input:checkbox').attr('checked', false);
        }
}
});

Upvotes: 0

Xaisoft
Xaisoft

Reputation: 46641

$('input[type="checkbox"]').change(function() {
    if ($(this).is(':checked')) {
        $(this).parents('ul').siblings('input:checkbox').attr('checked', true);
    }
    else
    {
        $(this).parents('ul').siblings('input:checkbox').attr('checked', false);
    }
});

Here is a demo.

Upvotes: 1

Ender
Ender

Reputation: 15221

A combination of .closest() and .siblings() should get you what you are looking for. You'll want to select the closest ancestor of the checked input which is a sibling with the "parent" checkbox, then traverse to that checkbox. The code would look something like this:

$('input:checkbox').change(function() {
    //if you are using < jQuery 1.6, use .attr() instead of .prop()
    if (this.checked) {
        $(this).closest('ul').siblings('input:checkbox').prop('checked', true);
    }
});

Here is a live demo ->

Upvotes: 1

Related Questions