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)
We can use the dispatchEvent method on an element to trigger an event programmatically. We can write: const element = document. querySelector('input'); element.
To programmatically force an onchange event on an input with JavaScript, we use the Event constructor. const element = document. getElementById("input"); const event = new Event("change"); element.
document. querySelector('#test'). addEventListener('change', () => console.
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With