Sometimes, we want to listen to input value change with JavaScript.
In this article, we’ll look at how to listen to input value change with JavaScript.
How to listen to input value change with JavaScript?
To listen to input value change with JavaScript, we can call addEventListener to add the change event listener.
For instance, we write
<input type="text" name="thing" value="" />
to add an input.
Then we write
const doThing = (e) => {
console.log(e.target.value);
};
document.getElementsByName("thing")[0].addEventListener("change", doThing);
to select the input by its name attribute value with
document.getElementsByName("thing")[0]
Then we call addEventListener to listen to the change event with the doThing function, which is emitted when we change the input value.
In doThing, we get the input value with e.target.value.
Conclusion
To listen to input value change with JavaScript, we can call addEventListener to add the change event listener.