Selecting all text in HTML text input when clicked
Solution 1:
You can use this javascript snippet:
<input onClick="this.select();" value="Sample Text" />
But apparently it doesn't work on mobile Safari. In those cases you can use:
<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />
Solution 2:
The previously posted solutions have two quirks:
- In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.
- It's impossible to place the cursor at a desired point after focus.
Here's a complete solution that selects all text on focus, but allows selecting a specific cursor point after focus.
$(function () {
var focusedElement;
$(document).on('focus', 'input', function () {
if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
focusedElement = this;
setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
});
});