Reputation: 347
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
Reputation: 123739
use prop instead of attr.
$(".productcheckbox", list).prop("checked", this.checked);
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