introduction
This article will display how to select all text in input field on focused vanilla JS, React and Vue. Although the code to implement feature is different, concepts are same.
select()
method
The select()
method in HTMLInputElement
selects all text in input field including textarea.
HTML and Vanilla Js
html
<input onfocus="this.select();" value="Big abc" id="text-box" />
React
jsx
<input type='text' value='Some something' onFocus={e => e.target?.select()} />
Typescript
tsx
<input type='text' value='Some something' onFocus={e => (e.target as HTMLInputElement)?.select()} />
Vue 3
vue
<input @focus="$event.target?.select()" />
Typescript
vue
<input @focus="($event.target as HTMLInputElement)?.select()" />
setSelectionRange()
Method
If you would like to select some letters, you can use setSelectionRange()
method.
The setSelectionRange()
Method is also part of HTMLInputElement
' methods.
The select()
method only allows to select all text in field.
On the other hands, setSelectionRange()
can define start index and end index.
html
<input onfocus="this.setSelectionRange(2, 5);" value="Big abc" id="text-box" />
When you focus the input, words between index 2 and index are selected.