Wednesday, January 27, 2010

Fixing IE onChange event for checkboxes and radio buttons

In Internet Explorer (up to at least IE8) clicking a radio button or checkbox to change its value does not actually trigger the onChange event until the the input loses focus. On every other browser, when the value of the input changes, onChange is triggered.

This is quite annoying, for example, if you want to trigger some other page changes off of the selection of a radio button in a radio button group changing. Some may suggest using onClick instead, and while that may be sufficient for a checkbox, for radio buttons, this is not a good solution. The problem is that onClick will fire when you click the radio button that is already selected, so you'll get your code triggered even when the value doesn't change.

Here's a quick hack that worked for me. On IE, handle the onClick event of radio and checkboxes and have it blur and re-focus the input element. This will trigger it to signal the onChange event like you'd expect from a decent browser. Then, you can go about your business using the onChange event like you should, and it will work correctly for you across the popular browsers. (WARNING: Of course, if you have other code triggered off of the blur and focus events, your mileage may vary.)

Here's an example of how you might do this using jQuery:


if ($.browser.msie) {
$(function() {
$('input:radio, input:checkbox').click(function() {
this.blur();
this.focus();
});
});
}

9 comments:

Anonymous said...

Thank you. :)
It works.

Anonymous said...

Thanks a lot !

Anonymous said...

Hopefully nobody has to care about support IE8 anymore, but I do and found you article useful. Though, dug a little deeper and found that you can use the 'properychange' event for IE8 and below. More info: http://stackoverflow.com/a/8926190/224139

Anonymous said...

Great fix ! Thank you

Anonymous said...

Thank you so much... you just saved my weekend! I'm a PHP/MySQL guy and had no idea that IE8 handled onchange and onclick differently.

Awoth said...

Thank you, this is much clearer explanation and better solution than others I tried to use.

Anonymous said...

Thanks working fine

erectile dysfunction remedies said...

I am in fact grateful to the owner of this website who has shared this wonderful piece of writing at at this place.

ed meds said...

We are a gaggle of volunteers and opening a brand new scheme in our community. Your site offered us with helpful information to work on. You have done an impressive job and our entire neighborhood shall be thankful to you.