You can select all text in an HTML <input>
element in the following ways:
#Select All Input Text When It's Clicked On
To select all text in an HTML <input>
element when it's clicked on, you can use the HTMLInputElement.select()
method, for example, in the following way:
<input
type="text"
value="Hello World!"
onclick="this.select()"
/>
Alternatively, you may use the HTMLInputElement.setSelectionRange()
method to achieve the same:
<input
type="text"
value="Hello World!"
onclick="this.setSelectionRange(0, this.value.length)"
/>
If you do not wish to inline JavaScript, you may create an event handler function for the click event, for example, like so:
const input = document.getElementById('foo');
input.addEventListener('click', function (e) {
e.target.select();
});
Or, alternatively, you can do the same using HTMLInputElement.setSelectionRange()
, for example, like so:
const input = document.getElementById('foo');
input.addEventListener('click', function (e) {
const target = e.target;
target.setSelectionRange(0, target.value.length);
});
You will have to replace "foo
" with the value you assign to the id
attribute of the <input>
element.
#Select All Input Text When a Button is Clicked
Consider you have the following <input>
and a "select all" <button>
element:
<input type="text" id="foo" value="Hello world!" />
<button onclick="selectAllText('foo')">Select All</button>
You could implement the "selectAllText()
" function (which is called when the button is clicked) as follows:
function selectAllText(id) {
const input = document.getElementById(id);
input.focus();
input.select();
}
Or, alternatively, you could use HTMLInputElement.setSelectionRange()
to achieve the same:
function selectAllText(id) {
const input = document.getElementById(id);
input.focus();
input.setSelectionRange(0, input.value.length);
}
Calling HTMLElement.focus()
is important as just using HTMLInputElement.select()
(or HTMLInputElement.setSelectionRange()
) will not necessarily focus the input.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.