10

Rather frustrating time here with IE9. This code works in IE7/8, but not 9.

document.getElementById('id').fireEvent("OnChange");

Any insight as to why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tyler
  • 19,113
  • 19
  • 94
  • 151

1 Answers1

25

In IE versions >= 9 and all other browsers you should use the dispatchEvent method:

var event = document.createEvent("HTMLEvents");
event.initEvent("change",true,false);

document.getElementById("id").dispatchEvent(event);

Check out http://jsfiddle.net/QKsvv/

Strelok
  • 50,229
  • 9
  • 102
  • 115
  • 1
    By checking `if (id.dispatchEvent)` then `else if (id.fireEvent)` I can now use the non-ie8 code to work for ie9. Looks like IE is finally catching on? – Tyler Mar 15 '12 at 06:07
  • That's right. You can extract the firing code into a separate method that will handle all browsers. – Strelok Mar 15 '12 at 06:08
  • 4
    As additional information, this only works for elements that are in the live DOM. If you dynamically make objects and want to simulate things like clicks on them using dispatchEvent, you *have* to add them to the DOM first. If you don't, you can still dispatch events, but you'll be tearing your hair out wondering why the function runs successfully without triggering your event handler. – Mike 'Pomax' Kamermans Jan 25 '13 at 22:24