Categories
JavaScript Answers

How to Listen to Input Value Change with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *