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();};
  }
 }
}

11 comments:

Robert said...

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.

Anonymous said...

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.

Leo Horie said...

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.

Leo Horie said...
This post has been removed by the author.
Anthony Ettinger said...

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

Peter Mouland said...

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

Marino said...

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.)

Me said...

Wouldn't blurring immediately break keyboard navigation though?

JasonJustian said...
This post has been removed by the author.
JasonJustian said...

> Wouldn't blurring immediately
> break keyboard navigation though?

Then:

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

Me said...

Pretty sure that would fire myFunction() twice in Firefox