Selecting all text in HTML text input when clicked

+2 votes
41 views
asked Dec 15, 2012 in HTML by john (4,220 points)

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 display, the text contains the "please enter the user Id. however, I found that the user need to click 3 clicks in order to select all the text (in this case is the "please enter the user ID"). Is it possible to select all the text only one click?

// Update ---------------------------

Sorry forget to say that, I must use the input type="text"

1 Answer

+1 vote
answered Dec 15, 2012 by kalpana (3,995 points)

 

The script is really very simple. Text field must have unique identifier, this indentifier will be passed to the SelectAll() function. The function call only two methods: focus() and select().

<script type="text/javascript">
function SelectAll(id)
{
    document.getElementById(id).focus();
    document.getElementById(id).select();
}
</script>

Textarea:<br>
<textarea rows="3" id="txtarea" onClick="SelectAll('txtarea');" style="width:200px" >This text you can select all by clicking here </textarea>

Input TextBox:<br>
<input type="text" id="txtfld" onClick="SelectAll('txtfld');" style="width:200px" value = "This text you can select all" />
 
...