We have an input type = "number"
and we have set an onChange
method.
The default value of the input is 0.
Then we change the value programatically to say, 10.
Now we change the value manually to 0 again.
The onChange
Method is not called on the manually made change. I think that's because the event wasn't called when we changed their value programmatically to 10. So in a way the control thinks that the value still is 0.
This happens only when I set manually the value to the value it was having BEFORE the programmatic change. If I use any other value to make the manual change, the onChange
event is triggered correctly.
document. querySelector('#test'). addEventListener('change', () => console.
onchange is not fired when the value of an input is changed. It is only changed when the input's value is changed and then the input is blurred. What you'll need to do is capture the keypress event when fired in the given input. Then you'll test the value of the input against the value before it was keypressed.
We can trigger the change event programmatically on an input element with the Event constructor. Then we can call the dispatchEvent method to dispatch the event.
Autofill does not trigger onChange.
Programatically changing a form control's value doesn't trigger its change handler, probably because the change event was specified as occuring after the user had changed the value and the control lost focus. Programmatic changes didn't follow that sequence (programmatically setting focus and blur to imitate user actions didn't help, though a programmatic change event could be dispatched on the element).
HTML5 introduced a new input event that fires whenever an input receives user input:
<input id="i0" oninput="alert(this.value);" value="">
You could use that instead of onchange, but it fires on each keypress and also if text is pasted or dragged to the input.
Note however that no browser fully supports HTML5 (and probably never will, since it's a moving target), so you will need to provide feature testing and a fall back mechanism should the input event not be supported.
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