Selecting all text in HTML text input when clicked

The previously posted solutions have two quirks:

  1. In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.
  2. 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.
    });
});

You can use the JavaScript .select() method for HTMLElement:

<label for="userid">User ID</label>
<input onClick="this.select();" value="Please enter the user ID" id="userid" />

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" id="userid" />