Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 572
Subin Jacob Avatar asked Apr 27 '13 09:04

Subin Jacob


People also ask

How do you programmatically trigger change events?

We can use the dispatchEvent method on an element to trigger an event programmatically. We can write: const element = document. querySelector('input'); element.

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

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.

How can I trigger an Onchange event manually in JavaScript?

document. querySelector('#test'). addEventListener('change', () => console.


1 Answers

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'.

like image 190
Nux Avatar answered Sep 23 '22 09:09

Nux