I have a tree build with ul and li. Each li has an checkbox with some text. I need to check all child elements when the parent element is checked. I did it with following code, which works in FF and Chrome but not in IE...
function checkSC(el){
var $parent = $(el).parent();
$($parent).find('input[type="checkbox"]').attr("checked", el.checked);
}
The html looks like this:
<ul id="treeUL" class="treeview-black treeview">
<li class="collapsable">
<div class="hitarea collapsable-hitarea"></div>
<input type="checkbox" onchange="checkSC(this)" value="26" name="开发者_运维技巧chkComm">
Conseil d'Administration
<ul>
<li>
<input type="checkbox" onchange="checkSC(this)" value="29" name="chkComm[29]">
Bureau
</li>
<li>
<input type="checkbox" onchange="checkSC(this)" value="31" name="chkComm[31]">
Comité de Direction
</li>
<li class="last">
<input type="checkbox" onchange="checkSC(this)" value="62" name="chkComm[62]">
Administrateurs Suppléants
</li>
</ul>
</li>
Use onclick instead. IE seems to wait until you've blurred the checkbox. Also, as long as you are using jQuery, use that to assign event handlers to objects instead of inline functions.
$(document).ready( function() {
$("input[type='checkbox']").click( function() {
$(this).parent().find('input[type="checkbox"]').attr("checked", this.checked);
});
});
You may want to alter the selector if you are only adding this handler to specific checkboxes.
Try 'onclick' in place of 'onchange'. onchange is not a valid event for checkbox. see http://www.w3schools.com/jsref/event_onchange.asp
$parent is a jQuery object already. You don't need to wrap it in another jQuery obj. It's the same of doing:
$( $("#target_id") )
I think the problem might come from the this
keyword used in your onchange function.
This article https://forloop.co.uk/blog/event-internals-in-jquery-part-one which explains how jQuery handles events as an interesting warning about the difference between models for how this
is interpreted in events:
What is this inside the handler function?
One of the biggest differences between the W3C and IE models is what the this keyword (the function context) refers to inside the event handler function; in the W3C model, this is a reference to the element on which the event handler is bound but in IE, this refers to the global object (the window object in browsers). This can really trip you up (pun intended) if you're not paying attention!
The solution would be to bind your handler using jQuery and thus not having to deal with the different browsers dissimilarities.
精彩评论