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"


You can use this javascript snippet:

<input onClick="this.select();" value="Sample Text" />

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

The previously posted solutions have two quirks:

  • In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.
  • 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(); }, 50); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
                });
            });
    

    Html (you'll have to put the onclick attribute on every input you want it to work for on the page)

     <input type="text" value="click the input to select" onclick="this.select();"/>
    

    OR A BETTER OPTION

    jQuery (this will work for every text input on the page, no need to change your html):

    <script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>  
    <script type="text/javascript">
        $(function(){
            $(document).on('click','input[type=text]',function(){ this.select(); });
        });
    </script>
    
    链接地址: http://www.djcxy.com/p/87600.html

    上一篇: JavaScript添加前导零

    下一篇: 单击时选择HTML文本输入中的所有文本