We can listen to input value change with JavaScript with the addEventListener
method.
For instance, if we have the following input:
<input type="text" name="name" value="" />
Then we can listen for changes in the value inputted by writing:
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
console.log(e.target.value);
});
We get the input element with document.querySelector
.
Then we call addEventListener
with 'change'
to listen to the change
event.
The 2nd argument of addEventListener
is an event listener function that lets us get the input value with e.target.value
.
Now when we type in the input box and move focus away from it, we see the inputted value logged.