Subin Jacob
Subin Jacob

Reputation: 4864

Trigger Change event when the Input value changed programmatically?

I have an Input in my form.

<input type="text" id="changeProgramatic" onchange="return ChangeValue(this);"/>

If I change the value in this textBox (changeProgramatic) using another JavaScript function it won't trigger the change Event.(Note: I'm passing 'this' into the method)

Upvotes: 120

Views: 206308

Answers (4)

askrynnikov
askrynnikov

Reputation: 771

When changing the value programmatically, you need to call the input event, not change event.

Note: The input event is fired every time the value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.

const el = document.getElementById('changeProgramatic');
el.value = 'New Value'
el.dispatchEvent(new Event('input', { 'bubbles': true }));

Upvotes: 17

Nux
Nux

Reputation: 10062

Vanilla JS solution:

var el = document.getElementById('changeProgramatic');
el.value = 'New Value'
el.dispatchEvent(new Event('change'));

Note that dispatchEvent doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).

So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for: typeof document.body.dispatchEvent === 'function'.

Upvotes: 226

Lahiru Chandima
Lahiru Chandima

Reputation: 24138

If someone is using react, following will be useful:

https://stackoverflow.com/a/62111884/1015678

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));

Upvotes: 21

kayz1
kayz1

Reputation: 7444

You are using jQuery, right? Separate JavaScript from HTML.

You can use trigger or triggerHandler.

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};

Upvotes: 42

Related Questions