Thursday, April 5, 2007

fixing the IE7 onchange bug on checkboxes

IE7 thinks "onchange" means "onblurafterchange", here's a way to get around it in checkboxes.

window.jscript/*@cc_on=@_jscript_version@*/
if (jscript==5.7) {//if IE7
 var inputs = document.getElementsByTagName("input"), i=-1, l=inputs.length;
 while (++i!==l) {
  var inputs_i=inputs[i];
  if ((inputs_i.type=="checkbox")&&inputs_i.onchange) {
   inputs_i._onchange=inputs_i.onchange;
   inputs_i.onchange=null;
   inputs_i.onpropertychange=function() {if (event.propertyName=='checked') this._onchange();};
  }
 }
}

14 comments:

  1. According to http://www.w3.org/TR/html4/interact/scripts.html, IE7s behavior seems ok:
    "The onchange event occurs when a control loses the input focus and its value has been modified since gaining focus."
    IF you wanted to react immediately, you would use onclick instead.

    ReplyDelete
  2. onchange means "onblurafterchange" in all other browsers I've tested as well, at least on text inputs. Not that I think it's a good thing.

    ReplyDelete
  3. Problem is: clients > standards.
    Not to mention that triggering events on blur after change in radio boxes and check boxes isn't very user friendly.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. I'm of the opinion onchange should trigger before the object is blurred...which works in FF/Opera/Safari, but not in IE7.

    ReplyDelete
  6. robert, onClick doesn't work as expected on checkboxes, think about when the user clicks the checkbox, but before releases s/he moves the mouse away. i agree with anthony! and this little beauty did the trick perfectly! thanks

    ReplyDelete
  7. I solved it this way:

    onchange="myFunction()" onclick="blur()"

    Ofcourse if you have used it 100 times or more this is not easy to adapt. I only used it 2 times so far, so an easy fix.
    Also the blurring is imo prettier then leaving the selection stand (same as when clicking a button, onclick="blur()" is always a nice thing to do.)

    ReplyDelete
  8. Wouldn't blurring immediately break keyboard navigation though?

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. > Wouldn't blurring immediately
    > break keyboard navigation though?

    Then:

    onchange="myFunction()" onclick="if (this.onchange) {this.onchange();}"

    ReplyDelete
  11. Pretty sure that would fire myFunction() twice in Firefox

    ReplyDelete
  12. Dont use onchange for the checkbox. please use "onclick" for checkbox always. Because checkbox always change when you click.

    ReplyDelete
  13. >Dont use onchange for the checkbox. please use "onclick" for checkbox always. Because checkbox always change when you click.

    But there's a thing called Label.. i want to use onChange

    ReplyDelete
  14. Solution:

    onChange="action();" onFocus="this.blur()"

    ReplyDelete