Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually changing value does not trigger onChange event if the value was changed before programmatically

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.

like image 684
sebastian rivas godoy Avatar asked Jun 12 '12 23:06

sebastian rivas godoy


People also ask

How do you trigger Onchange event manually?

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

Why is Onchange not working?

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.

How do you trigger a change in an event?

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.

Does autofill trigger Onchange?

Autofill does not trigger onChange.


1 Answers

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.

like image 157
RobG Avatar answered Oct 25 '22 17:10

RobG