Categories
JavaScript Answers

How to auto select an input field and the text in it on page load with JavaScript?

Spread the love

Sometimes, we want to auto select an input field and the text in it on page load with JavaScript.

In this article, we’ll look at how to auto select an input field and the text in it on page load with JavaScript.

How to auto select an input field and the text in it on page load with JavaScript?

To auto select an input field and the text in it on page load with JavaScript, we can use the focus and select methods.

For instance, we write

<input id="myTextInput" value="Hello world!" />

to add an input.

Then we write

const input = document.getElementById("myTextInput");
input.focus();
input.select();

to select the input with getElementById.

Then we call focus to focus on the input.

And we call select to select the input value.

Conclusion

To auto select an input field and the text in it on page load with JavaScript, we can use the focus and select methods.

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 *