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.