Vegard Innerdal
Vegard Innerdal

Reputation: 347

Why do my nested checkboxes only work once?

I'm adjusting an existing page where there are nested checkboxes, like this:

<ul>
    <li>
        <label><input type="checkbox" class="categorycheckbox">Group 1</label>
        <ul>
            <li>
                <label><input type="checkbox" class="productcheckbox">Item 1</label>
            </li>
            <li>
                <label><input type="checkbox" class="productcheckbox">Item 2</label>
            </li>
        </ul>
    </li>
    <li>
        <label><input type="checkbox" class="categorycheckbox">Group 2</label>
        <ul>
            <li>
                <label><input type="checkbox" class="productcheckbox">Item 1</label>
            </li>
            <li>
                <label><input type="checkbox" class="productcheckbox">Item 2</label>
            </li>
        </ul>
    </li>
</ul>

And so on. I'm using jQuery to give the users the ability to select/deselect all child inputboxes, like this:

var updateCheckedState = function () {
    var list = $(this).closest("li").find("ul");
    $(".productcheckbox", list).attr("checked", this.checked);
};

$(".categorycheckbox").change(updateCheckedState);

This works for checking once and unchecking once for each group. Then it stops working, and I don't understand why. I've created a fiddle: http://jsfiddle.net/AQ76y/

Upvotes: 0

Views: 79

Answers (1)

PSL
PSL

Reputation: 123739

use prop instead of attr.

$(".productcheckbox", list).prop("checked", this.checked);

Fiddle

Because sometimes updating the attribute does not update the element property but using an prop and updating the property it is ensured that it will work across browsers.

In earlier verisons of jquery attr used to do the work of prop, so it used to work then

Upvotes: 4

Related Questions