You need to add EventListener() method
Solution 1 :
Solution 2 :
You can add an event listener.
document.getElementById("fooId").addEventListener("change", func);
function func(e){
alert(e.target.value)
}
<input type="text" id="fooId"/>
Solution 3 :
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);
}
}
Solution 4 :
this should help.
https://www.w3schools.com/jsref/event_onchange.asp
else if you have more specific need, then share that
Solution 5 :
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>
Problem :
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?
Comments
Comment posted by Avinash Dalvi
same answer but earlier than me. Upvoting this answer because thoughts is same. Only provide example.
Comment posted by Mostafa Ahmed
I put link in my answer to try it out by himself
Comment posted by Avinash Dalvi
Good thought! @mostafa-ahmed
Comment posted by Avinash Dalvi
same answer but timing same. Upvoting this answer because thoughts is same.