When I use onChange(), it triggers only when user changes something in an input field. I want it to trigger even when JavaScript changes something in an input field. How can I achieve this?
Asked
Active
Viewed 204 times
5 Answers
1
You can add an event listener.
document.getElementById("fooId").addEventListener("change", func);
function func(e){
alert(e.target.value)
}
<input type="text" id="fooId"/>

ABGR
- 4,631
- 4
- 27
- 49
-
same answer but timing same. Upvoting this answer because thoughts is same. – Avinash Dalvi Jun 14 '20 at 10:03
1
You need to add EventListener() method

Mostafa Ahmed
- 474
- 7
- 16
-
same answer but earlier than me. Upvoting this answer because thoughts is same. Only provide example. – Avinash Dalvi Jun 14 '20 at 10:04
-
1
-
1
Update:
So user https://www.webdeveloper.com/u/Sempervivum helped me and found this script originaly posted by Shawn Regan here: detect value change in input tag with vanilla javascript and MutationObserver which does exactly what I was looking for. You can find working demo here: https://jsfiddle.net/zyx54/hdn4txry/ That script here:
let registered = [];
let setDetectChangeHandler = function(field) {
if (!registered.includes(field)) {
let superProps = Object.getPrototypeOf(field);
let superSet = Object.getOwnPropertyDescriptor(superProps, "value").set;
let superGet = Object.getOwnPropertyDescriptor(superProps, "value").get;
let newProps = {
get: function() {
return superGet.apply(this, arguments);
},
set: function (t) {
let _this = this;
setTimeout( function() { _this.dispatchEvent(new Event("change")); }, 50);
return superSet.apply(this, arguments);
}
};
Object.defineProperty(field, "value", newProps);
registered.push(field);
}
}
0
this should help. https://www.w3schools.com/jsref/event_onchange.asp else if you have more specific need, then share that

jojitoon
- 146
- 1
- 2
0
This way to add eventlistner to input.
var sampleFunction = function(values){
document.getElementById("sample").value = "New text";
}
var input = document.getElementById("sample");
input.addEventListener('change', (event) => {
console.log("afafaf");
});
<div>
<input type="text" id="sample" onchange="sampleFunction(this.value)"/>
</div>
<span id="changetext" ></span>

Avinash Dalvi
- 8,551
- 7
- 27
- 53