You can use the excellent event.simulate.js to do this. This script does depend on the Prototype.js library, though.
If you'd want to this without relying on an external library, take a look at the fireEvent
and createEvent
functions. A simple demonstration of how you could implement this:
function triggerEvent(element, eventName)
{
if (document.createEvent)
{
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, true);
return element.dispatchEvent(evt);
}
if (element.fireEvent)
return element.fireEvent('on' + eventName);
}
triggerEvent(document.getElementById('myTextbox', 'change'));
Using event.simululate.js, you would do it like this:
Event.simulate('myTextbox', 'change');
A similiar question was asked here: http://stackoverflow.com/questions/460644/trigger-an-event-with-prototype.
EDIT: although it is possible to use document.getElementById('myTextbox').change()
, I would not recommend doing it, as it makes your code less flexible. When attaching onChange events to the textbox, these would not trigger when manually calling the change() event. Using the above method, events will propagate, just as if the event was a user-triggered one.