Sometimes, we may want to select all the contents of a textbox when it receives focus.
In this article, we’ll look at how to select all the contents of a textbox when it receives focus.
Select All Contents of a Textbox When it Receives Focus
We can select all the contents of a textbox when it receives focus by listening to the focus
event.
For instance, we can write the following HTML:
<input type="text" value="test" />
And the following JavaScript code:
const input = document.querySelector('input')
input.addEventListener('focus', () => {
input.select();
})
input.addEventListener('mouseup', (e) => {
e.preventDefault()
})
We get the input with querySelector
.
Then we call addEventListener
with 'focus'
as the first argument to listen to the focus event.
Then we call the input’s select
method to select all the text inside the input when we click on it to focus on the textbox.
Also, we add a mouseup
event listener and call e.preventDefault
to stop its default action, which is to deselect on click.
Select Input Text in a Text Input with React
We can do the same thing with React easily.
For instance, we can write:
import React from "react";
export default function App() {
return (
<div>
<input type="text" value="test" onFocus={(e) => e.target.select()} />
</div>
);
}
We just pass in a function that calls e.target.select
to select all the text in the input as the value of the onFocus
prop.
e.target
is the input element so we can call select
on it to select all the text.
Conclusion
We can select all the text in an input box when we focus on it by writing a few lines of JavaScript code.