Trigger Change event when the Input value changed programmatically?

JavascriptJqueryHtml

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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][1]). 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][2] 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'.

[1]: http://caniuse.com/#feat=dispatchevent "caniuse.com dispatchevent" [2]: https://www.quirksmode.org/css/condcom.html

Solution 2 - Javascript

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');
};

Solution 3 - Javascript

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 }));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSubin JacobView Question on Stackoverflow
Solution 1 - JavascriptNuxView Answer on Stackoverflow
Solution 2 - Javascriptkayz1View Answer on Stackoverflow
Solution 3 - JavascriptLahiru ChandimaView Answer on Stackoverflow