204

How do I programmatically force an onchange event on an input?

I've tried something like this:

var code = ele.getAttribute('onchange');
eval(code);

But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.

8 Answers 8

303
+250

Create an Event object and pass it to the dispatchEvent method of the element:

var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);

This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.


By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do.

If you want the event to bubble, you need to pass a second argument to the Event constructor:

var event = new Event('change', { bubbles: true });

Information about browser compability:

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, the MDN Creating and triggering events is a good resource!
This is how to do it properly, natively. Supported in all browsers now: caniuse.com/#feat=dispatchevent
Im trying to do the equivalent on IE11 but it's not working when trying to change a reactjs input field. var evt = document.createEvent('CustomEvent'); evt.initCustomEvent('input', true, false, { }); elem.dispatchEvent(evt);
Why is everyone saying this is the best answer? According to the linked Event doc, even the current version of IE still doesn't support this.
{ bubbles: true } this was the fix for my issue. Thanks
|
110

In jQuery I mostly use:

$("#element").trigger("change");

3 Comments

tihs helped me! I was setting the value of a checkbox (checked or not) using code and the event was not firing in IE at all no matter what i did. I tried blur() focus() and a few other things. after i set the value i called trigger and i added a click event to call trigger as well. It causes multiple fires but it doesnt matter to me. In IE I add checkboxes through code and you have to click on them twice before the change event fires. Thanks for this tip.
As an update, $("#element").change(); does the same thing since jquery 1.0.
Note that this does NOT trigger a native onchange. It will only fire on all the onchange listeners that were bound through jQuery!
65

ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:

document.getElementById("test").onchange()

Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly

11 Comments

eval for objectifying JSON ;)
json2.js for objectifying JSON! JSON.parse is already available on modern browsers
This technique only works if the change handler was attached by setting "onchange". It does not generate a 'real' event that triggers w3c or microsoft event handlers. See the link for more details.
I think this answer is outdated now, Miscreant's answer using new Event(...) and dispatchEvent is the right solution nowadays, it seems.
This answer is obsoleted; the code above will not work if you used Element.addEventListener to handle events. To achieve it in a modern way, see @Miscreant's answer.
|
25

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

3 Comments

I like this method of browser detection (by object detection) better than the example I provided.
This do not work anymore for Firefox 23 : "element.dispatchEvent is not a function"
Hi fellow Googlers. It's 2016! Nowadays we write code like element.dispatchEvent(new Event('change', true, true)) instead of all that arcane and mostly deprecated createEvent and initEvent stuff.
4

This is the most correct answer for IE and Chrome::

var element = document.getElementById('xxxx');
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', false, true);
element.dispatchEvent(evt);

Comments

2

Taken from the bottom of QUnit

function triggerEvent( elem, type, event ) {
    if ( $.browser.mozilla || $.browser.opera ) {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
            0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem.dispatchEvent( event );
    } else if ( $.browser.msie ) {
        elem.fireEvent("on"+type);
    }
}

You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.

To use this function:

var event;
triggerEvent(ele, "change", event);

This will basically fire the real DOM event as if something had actually changed.

Comments

-1

The change event in an input element is triggered directly only by the user. To trigger the change event programmatically we need to dispatch the change event.

The question is Where and How?

"Where" we want the change event to be triggered exactly at the moment after a bunch of codes is executed, and "How" is in the form of the following syntax:

const myInput = document.getElementById("myInputId");

function myFunc() {
  //some codes
  myInput.dispatchEvent(new Event("change"));
}

In this way, we created the change event programmatically by using the Event constructor and dispatched it by the dispatchEvent() method. So whenever myFunc() method is invoked, after the //some codes are executed, our synthetic change event is immediately triggered on the desired input element.‍

Important result: Here, the change event is triggered by executing the //some codes in myFunc() instead of changing the input value by the user (default mode).

Comments

-8

Using JQuery you can do the following:

// for the element which uses ID
$("#id").trigger("change");

// for the element which uses class name
$(".class_name").trigger("change");

1 Comment

undefined is not a function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.