0

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);
        }
    });
});
scottrakes
  • 735
  • 9
  • 26

3 Answers3

1

For me the problem was I was just using checked and not checked="checked". Dumb mistake, but hopefully that helps someone.

animuson
  • 53,861
  • 28
  • 137
  • 147
Matt
  • 11
  • 1
0

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" />
NotMe
  • 87,343
  • 27
  • 171
  • 245
0

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");
}
a7drew
  • 7,801
  • 6
  • 38
  • 39
  • 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 Jul 13 '10 at 10:25
  • 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? – a7drew Jul 13 '10 at 16:10