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>
  </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>

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.