Appearance
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:
JavaScript select all text in HTML text input when clicked
html
<!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>For older browsers or specific compatibility needs, you can use:
JavaScript select all text in HTML text input when clicked
html
<!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.
Using inline event attributes can clutter HTML. A cleaner approach is to attach the selection logic to the focus event via JavaScript:
JavaScript select all text in HTML text input on focus
html
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<div>
Input Text:
<input id="input-tag" value="Sample Text" />
</div>
<script>
const inputElement = document.getElementById('input-tag');
inputElement.addEventListener('focus', function(e) {
inputElement.select()
})
</script>
</body>
</html>Tip: To allow users to adjust the cursor before all text is selected, wrap inputElement.select() in a setTimeout with a short delay (e.g., setTimeout(() => inputElement.select(), 0)).
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.