I have an input field I want to assign a new value and fire an .onchange() event. I did the following:
document.getElementById("range").value='500';
document.getElementById("range").onchange();
Where range is my input Id.
I get the following error:
Uncaught TypeError: Cannot read property 'target' of undefined
Is there a way to define the ‘target’?
Thank you
The error about
targetis because there’s code in the event handler that’s trying to read thetargetproperty of theEventobject associated with the change event. You could try passing in an faux-Event to fool it:or, if you can, change the handler code to use
thisinstead ofevent.target. Unless you are using delegation (catching change events on child object from a parent, something that is troublesome for change events because IE doesn’t ‘bubble’ them), the target of the change event is always going to be the element the event handler was registered on, makingevent.targetredundant.If the event handler uses more properties of
Eventthan justtargetyou would need to fake more, or go for the ‘real’ browser interface to dispatching events. This will also be necessary if event listeners might be in use (addEventListener, orattachEventin IE) as they won’t be visible on the directonchangeproperty. This is browser-dependent (fireEventfor IE,dispatchEventfor standards) and not available on older or more obscure browsers.