27. sep. 2006

Fire onChange in Javascript programmatically

I want to fire onChange method on an object programmatically in Javascript.

FireFox and Internet Explorer handles this very differently.
If you for example sets the value on an object you might expect that the onChange method is fired, but sorry... no firering...

The solution is this in Javascript:
function newValueForObject {
var myObject = document.getElementById(nameOfObject);
myObject.value = 'a new value';

if (myObject.hasAttribute) { // Firefox
if(myObject.hasAttribute("onchange")){
myObject.onchange();
}
} else if (myObject.onchange) { // IE
var newEvt = document.createEventObject();
myObject.fireEvent("onchange", newEvt);
}
}