How to Select All Text in HTML Text Input When Clicked Using JavaScript
It is pretty simple to select whole text on just a single click. You can use the following JavaScript code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<div>
Input Text:
<input onClick="this.select();" type="text" value="Sample Text">
</div>
</body>
</html>
However, it does not work on mobile Safari. In such cases, you can use:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<div>
Input Text:
<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />
</div>
</body>
</html>
The HTMLInputElement.select() method selects the entire text in a <textarea> element or <input> element that includes a text field.
But it becomes impossible to place the cursor at a desired point after focus. Here is another solution that combines all text selection on focus and as well as allows selecting a specific cursor point after focus:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<script src="https://code.jquery.com/jquery-3.5.0.min.js">
</script>
</head>
<body>
<div>
Input Text:
<input value="Sample Text" />
</div>
<script>
$(function() {
let focusedElement;
$(document).on('focus', 'input', function() {
if(focusedElement == this) return; // already focused, return so the user can place the cursor at a specific entry point
focusedElement = this;
setTimeout(function() {
focusedElement.select();
}, 100); //Select all text in any field in focus for easy re-entry. The delay is a bit to allow the focus to “stick” to the selection.
});
});
</script>
</body>
</html>
The HTMLElement.focus() method sets focus on the given element if it can be focused. By default, the focused element will receive keyboard and similar events.