How to track onchange as we type in input type=”text” with JavaScript?

Spread the love

Sometimes, we want to track onchange as we type in input type="text" with JavaScript.

In this article, we’ll look at how to track onchange as we type in input type="text" with JavaScript.

How to track onchange as we type in input type="text" with JavaScript?

To track onchange as we type in input type="text" with JavaScript, we can listen for the input’s input event.

For instance, we write

<input id="source" />
<div id="result"></div>

to add an input and a div.

Then we write

const source = document.getElementById("source");
const result = document.getElementById("result");

const inputHandler = (e) => {
  result.innerHTML = e.target.value;
};

source.addEventListener("input", inputHandler);

to select tjhe input and div with getElementById.

Then we call addEventListener to listen to the input event on the source input.

inputHandler is called as we type in the input.

In it, we set the content of the div to the input value with

result.innerHTML = e.target.value

e.target.value has the input’s value.

Conclusion

To track onchange as we type in input type="text" with JavaScript, we can listen for the input’s input event.

Leave a Reply

Your email address will not be published.