Categories
JavaScript Answers

How to get text of an input text box during onKeyPress with JavaScript?

Spread the love

Sometimes, we want to get text of an input text box during onKeyPress with JavaScript.

In this article, we’ll look at how to get text of an input text box during onKeyPress with JavaScript.

How to get text of an input text box during onKeyPress with JavaScript?

To get text of an input text box during onKeyPress with JavaScript, we can handle the input event.

For instance, we write

<input type="text" onInput="showCurrentValue(event)" />
<br />
<span id="label"></span>

to add an input and a span

Then we write

function showCurrentValue(event) {
  const value = event.target.value;
  document.getElementById("label").innerText = value;
}

to define the showCurrentValue function that takes the input value from event.target.value.

And then we get the span with getElementById and set the span’s innerText to value to show the input value in the span.

Conclusion

To get text of an input text box during onKeyPress with JavaScript, we can handle the input event.

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 *