18

The "onchange" event is triggered only when the USER enters some value. Why isn't possible to fire the event when I change the value automatically via Javascript ? Is there an alternative ?

Animation:

enter image description here

Code:

<!DOCTYPE html>

<html>
    <head>
        <script>
            document.addEventListener ("DOMContentLoaded", function () {
                var input = this.getElementsByTagName ("input")[0];
                var div = this.getElementsByTagName ("div")[0];
                var i = 0;
                var seconds = 5;

                div.innerHTML = "The following input should fire the event in " + seconds + " seconds";

                var interval = window.setInterval (function () {
                    i ++;

                    if (i === seconds) {
                        window.clearInterval (interval);

                        input.value = "Another example";

                        div.innerHTML = "Nothing ! Now try change the value manually";
                    }
                    else {
                        div.innerHTML = "The following input should fire the event in " + (seconds - i) + " seconds";
                    }
                }, 1000);

                input.addEventListener ("change", function () {
                    alert ("It works !");
                }, false);
            }, false);
        </script>

        <style>
            body {
                padding: 10px;
            }

            div {
                font-weight: bold;
                margin-bottom: 10px;
            }

            input {
                border: 1px solid black;
                border-radius: 3px;
                padding: 3px;
            }
        </style>

        <title>Event</title>
    </head>

    <body>
        <div></div>
        <input type = "text" value = "Example" />
    </body>
</html>

Thanks

Caio
  • 3,178
  • 6
  • 37
  • 52
  • You have to manually fire the event after changing the value. See this question: http://stackoverflow.com/q/2490825/615754 – nnnnnn Jan 09 '12 at 13:56
  • when you change the input value with javascript why no firing some event too? why do you want to use onchange? the onchange is for user input the rest you can handle without by yourself. – ggzone Jan 09 '12 at 13:59

4 Answers4

25

The vast majority of the time, you don't want an event to be fired when you change the value with code. In those cases where you do, you can fire a synthetic event on modern browsers via dispatchEvent. More here.

So in your specific example:

input.value = "Another example";
var event = document.createEvent("UIEvents"); // See update below
event.initUIEvent("change", true, true);      // See update below
input.dispatchEvent(event);

Live demo

Update: As Benjamin noted, since the above was written, initUIEvent has been replaced with the UIEvent constructor, so that would be:

input.value = "Another example";
var event = new UIEvent("change", {
    "view": window,
    "bubbles": true,
    "cancelable": true
});
input.dispatchEvent(event);

Live demo

Alternately, you can always just call whatever function you've bound to the change event directly, which is usually what I'd do. But sometimes you want to use actual events (for instance, when using the observer pattern) and ensure that anyone who is listening for the change is notified.

vsync
  • 118,978
  • 58
  • 307
  • 400
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I am using your updated answer and It works like a charm, but it makes my app too slow, the same action when done with jquery's trigger(), its fast. What could be the reason? and how can I improve the performance? – Abhinav May 30 '17 at 13:17
  • If one's filling multiple hidden inputs, should one create multiple events and fire them all, or should just 1 event be created and fired multiple times? – Hassan Baig Apr 04 '18 at 23:08
  • 1
    @HassanBaig: That's entirely up to you. Again, it's unusual to want to fire an event when changing an input with code anyway, and in your example, hidden inputs never fire change events anyway. So any need to do so will be entirely specific to your code, as will the one-vs.-many decision. – T.J. Crowder Apr 05 '18 at 07:18
5

Note that initUIEvent has been deprecated and removed from Web Standards as stated: developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent

This is the same except that it doesn't use initUIEvent:

input.value = 'Another example';
var event = new UIEvent('change', {
    'view': window,
    'bubbles': true,
    'cancelable': true
});
input.dispatchEvent(event);
Benjamin Intal
  • 2,748
  • 1
  • 25
  • 26
1

The code of Crowder only gave me an TypeError (Not enough arguments to UIEvent.initUIEvent). Change it to this:

input.value = "Another example";
var event = document.createEvent("UIEvents");
event.initUIEvent("change", true, true, window, 1);
input.dispatchEvent(event);

and it works.

Malte
  • 17
  • 4
  • Note that `initUIEvent` has been deprecated and removed from Web Standards as stated: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent – Benjamin Intal Jul 07 '15 at 10:38
1

If you are changing the value progammatically, you already know when this occurs, what's to say you can't call your own method, (the same perhaps that is called from the actual trigger event handler) when you change the value?

EDIT: otherwise, if you specifically need the actual Fire to occur, you can manually dispatch the event yourself too.

OnResolve
  • 4,016
  • 3
  • 28
  • 50
  • picture this: you have 1 function updating 5 inputs, each input when changed has to call a different function, everything is dynamic so you won't know the IDs and whats else.. best way is adding a change listener to each input that calls the function it needs, – bakz Jun 04 '17 at 20:56