Search code examples
javascripthtmltextinput

Selecting all text in HTML text input when clicked


I have the following code to display a textbox in a HTML webpage.

<input type="text" id="userid" name="userid" value="Please enter the user ID" />

When the page displays, the text contains the Please enter the user ID message. However, I found that the user needs to click 3 times in order to select all the text (in this case it is Please enter the user ID).

Is it possible to select the entire text with only one click?

Edit:

Sorry, I forgot to say: I must use the input type="text"


Solution

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

    userid.addEventListener(`focus`, () => userid.select());
    <label for="userid">User ID</label>
    <input value="Please enter the user ID" id="userid" />