Ajouve
Ajouve

Reputation: 10039

check checkbox in a list

I'd like to automatically uncheck or check children's checkboxes:

HTML:

<ul>
    <li>1 <input type='checkbox' /></li>
    <ul>
        <li>1.1 <input type='checkbox'' /></li>
    </ul>
    <ul>
        <li>1.1.1 <input type='checkbox' /></li>
    </ul>
</ul>

Javascript:

$('li input').change(function(){
    if($(this).is(":checked")){
        $(this).parent().next().children("li").children("input").attr("checked", true);
        console.log("checked")
    }else{
        $(this).parent().next().children("li").children("input").attr("checked", false);
        console.log("not checked")
    }
})

But it only works for the first occurence. I don't understand why because the 1.1 change and the event change is not triggered

http://jsfiddle.net/D8ZdU/

Thanks

Upvotes: 0

Views: 1608

Answers (3)

Ram
Ram

Reputation: 144719

You can use closest method:

$('ul input').change(function(){
   var $this = $(this).closest('ul');
   $this.add($this.nextAll()).find("input").prop("checked", this.checked);
})

http://jsfiddle.net/LpGsS/

Note that your markup need modofication why not using li elements?

<ul>
    <li>1 <input type='checkbox' /></li>
    <li>1.1<input type='checkbox' /></li>
    <li>1.1.1 <input type='checkbox' /></li>
</ul>

$('ul input').change(function(){
    $(this).parent().nextAll().find("input").prop("checked", this.checked);
})

http://jsfiddle.net/JjvKH/

Upvotes: 1

David Thomas
David Thomas

Reputation: 253446

If you correct your HTML, to the following:

<ul>
    <li>1 <input type="checkbox" />
        <ul>
            <li>1.1 <input type="checkbox" />
                <ul>
                    <li>1.1.1 <input type="checkbox" /></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Then the following jQuery works:

$('input:checkbox').change(
    function(){
        var state = this.checked ? true : false;
        $(this).next('ul').find('input:checkbox').prop('checked', state);
    });​

JS Fiddle demo.

The problems with your HTML are that a ul element is not a valid child of another ul, or ol, element. The only valid children of ul (and ol) is the li element, everything else is invalid, unless it's contained within an li.

References:

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

For the first checkbox, "parent" is the <li> that's in the outer <ul>. For the others, their "parent" is the <li> that's isolated in another <ul> and has no "next".

Upvotes: 0

Related Questions