views:

37

answers:

2

I am trying to setup a checkbox that checks all the child checkboxes, like a tree view. The following codes works great in Firefox and Chrome but in IE, it takes two clicks to get it to work. What am I missing?

HTML

<input type="checkbox" name="org" value="orgs" id="orgs" />
<label for="All">Organizations</label>

<ul id="orglist">
    <li>
            <input type="checkbox" name="org" value="1" id="1" />
            <label for="1">Org 1</label>
    </li>
    <li>
            <input type="checkbox" name="org" value="1" id="2" />
            <label for="2">Org 2</label>
    </li>
</ul>

Javascript/Jquery

$(document).ready(function () {
    $("#orgs").change(function () {

        if ($(this).attr("checked")) {
            $("#navform #orglist :checkbox").attr("checked", true);
        }
        else {
            $("#navform #orglist :checkbox").attr("checked", false);
        }
    });
});
A: 

Most likely the state of a checkbox is in doubt for IE. Try setting the checked property to false or whatever on initial page load. For example:

<input type="checkbox" name="or" value="1" id="1" checked="false" />
Chris Lively
A: 

Instead of looking for an attribute, let jQuery do more work:

if ($(this).is(":checked")) {
    $("#navform #orglist :checkbox").attr("checked", "checked");
}
else {
    $("#navform #orglist :checkbox").removeAttr("checked");
}
AndrewDotHay
Actually this should be `$("#navform #orglist :checkbox").attr("checked", this.checked);` if anything (or a `.each()`), don't let jQuery do "more work" use the faster DOM properties if available, generally speaking `$(this).is(":checked")` is extremely wasteful. [There are other cases this applies as well](http://stackoverflow.com/questions/3230727/jquery-optimization-best-practices/3230788#3230788)
Nick Craver
I'm still learning about jQuery optimization. What aspect is wasteful here? Is it in terms of milliseconds to perform the action and/or is it in terms of memory or computations necessary? Can you point me to some actual measurements?
AndrewDotHay