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
This seems to work for me (see this fiddle). Do you have any other code that may be the problem? How did you define your onchange handler?
Are you calling e.target in your onchange handler? I suspect this may be the issue... since you are doing the change programmatically, there is no corresponding window event.
Try using fireEvent or dispatchEvent (depending on browser) to raise the event:
from : http://www.mail-archive.com/jquery-en@googlegroups.com/msg44887.html
Generally, your code should work fine. There might be something else that's issuing the problem, though.
range
id is loaded by the time you run the code (e.g. you run it in document.ready).range
on the page?onchange()
function doing (could be helpful to post it here)?Apart from that, I would recommend using jQuery (if possible):
or just
http://api.jquery.com/change/
But as I mentioned, your case should work fine too: http://jehiah.cz/a/firing-javascript-events-properly
The error about
target
is because there's code in the event handler that's trying to read thetarget
property of theEvent
object 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
this
instead 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.target
redundant.If the event handler uses more properties of
Event
than justtarget
you 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
, orattachEvent
in IE) as they won't be visible on the directonchange
property. This is browser-dependent (fireEvent
for IE,dispatchEvent
for standards) and not available on older or more obscure browsers.