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"
I know this is old, but the best option is to now use the new
placeholder
HTML attribute if possible:This will cause the text to show unless a value is entered, eliminating the need to select text or clear inputs.
You can always use
document.execCommand
(supported in all major browsers)Selects all text in the currently focused element.
Note: When you consider
onclick="this.select()"
, At the first click, All characters will be selected, After that maybe you wanted to edit something in input and click among characters again but it will select all characters again. To fix this problem you should useonfocus
instead ofonclick
.If anyone want to do this on page load w/ jQuery (sweet for search fields) here is my solution
Based on this post . Thanks to CSS-Tricks.com
Here's a reusable version of Shoban's answer:
That way you can reuse the clear script for multiple elements.
The problem with catching the click event is that each subsequent click within the text will select it again, whereas the user was probably expecting to reposition the cursor.
What worked for me was declaring a variable, selectSearchTextOnClick, and setting it to true by default. The click handler checks that the variable's still true: if it is, it sets it to false and performs the select(). I then have a blur event handler which sets it back to true.
Results so far seem like the behavior I'd expect.
(Edit: I neglected to say that I'd tried catching the focus event as someone suggested,but that doesn't work: after the focus event fires, the click event can fire, immediately deselecting the text).