Friday, April 10, 2009

Select text in input box on user select or focus

A colleague of mine who is not very javascript (or for that matter jQuery aware) asked me to help him to do a little trick with jQuery. He needed to select the contents of the input box when user selects it (basically, when user focuses in the input field).

In case you're Googler looking for a way of getting input field's value, see the code snippet at the end of the post.

Selecting inputbox text on focus is easy and it's 3 lines of jQuery code. But it adds nice usability touch to your website. This "select all" behavior is browser default when you browse through form fields using TAB key, but when you click on the input text field it does not behave like that.

Here is jQuery code to select text inside an input field on user click or focus.

$("#myInputField").focus(function(){
    // Select input field contents
    this.select();
});

select() is a built in javascript method. It selects content of the field it is called on (in our case, an input field).

We can add this behaviour to all text input fields on the page by extending the jQuery selector.

// Add this behavior to all text input fields
$("input[type=text]").focus(function(){
    this.select();
});

Let's change the selector in the example above event more to add this behavior to all password and textarea fields as well.

// Add this behavior to all text input fields
$("input[type=text], input[type=password], textarea").focus(function(){
    this.select();
});

Also, we can improve our form usability by only selecting the contents of text fields, if their value have not been changed from their default values.

$("input[type=text], textarea").focus(function(){
    // Check for the change from default value
    if(this.value == this.defaultValue){
        this.select();
    }
});

The code above selects all text content of textarea if and only if it's value has changed from its' default value.

Just in case, you came here from search engines looking for a way to get input or textarea's contents, here is how to do it.

// Select the input field & call .val() method
$("input.username").val();

// For textarea, you need to call .html() method instead
$("textarea.comment").html();

22 comments:

  1. I could not get this code (first block) to select the contents of the input. The following did work, however:

    $('#myInputField').focus().select();

    For what it's worth, in case others run into the same issue. Thanks for the post, it got me pointed in the right direction!

    Brandon

    ReplyDelete
  2. Thanks, Brandon, you saved me.

    ReplyDelete
  3. @Brandon
    The code examples select the text only when focussed (ie. clicked on or tabbed into etc) which is what the author intended.

    If you just want the text to be selected then, yeah, your snippet works but so does the simpler:
    $('#myInputField').select();

    ReplyDelete
  4. I suggest you use this replacement:
    $('input[type="text"]')
    Since wrapping the attribute in quotes is the correct way to do it.

    ReplyDelete
  5. probably needed to wrap the current element with the jQuery object like

    $(this).select();

    I think it's a DOM object by default

    ReplyDelete
  6. Please note that with IE, in at least versions 7 and 8; if you intend on firing focus() immediately after document.ready() automatically, you may need to incorporate a delay() of at least 300ms (my web app required 500).

    ReplyDelete
  7. function selectTextboxContent(textbox)
    {
    setTimeout(function() { textbox.select(); }, 10);
    }
    onfocus="selectTextboxContent(this);"
    Try this Jquery also create issue in Chrome and Safari

    ReplyDelete
  8. Of course it's the default action when you tab into the field since your fingers are ready to type. When you click on a field, you have a precision cursor to point to where you want to click. If you wish to select all, you can click multiple times. You're pandering to n00bs.

    ReplyDelete
  9. I think the problem with this is that _this_ is a reference to the DOMNode and not a jQuery collection within the focus callback functions. Wrapping them before calling .select will correct this:

    $("#myInputField").focus(function(){
    // Select input field contents
    $(this).select();
    });

    // Add this behavior to all text fields
    $("input[type=text]").focus(function(){
    // Select field contents
    $(this).select();
    });

    ReplyDelete
  10. just a tip (without jQuery):
    input type="text" onClick="javascript:this.select();" />

    ReplyDelete
  11. On Chrome and Safari you need to return false on mouse up. Otherwise as soon as you release the mouse it unselects everything. So:

    $('#myInputField').mouseup(function(){return false;});

    ReplyDelete
  12. Brilliant! I simplified it further for any input fields with text:

    $(function() {

    $("input, textarea").focus(
    function()
    {
    // Check for the change
    if(this.value == this.defaultValue)
    { this.select();
    }
    });
    });

    ReplyDelete
  13. This worked better for me.

    $(".select_all").click(function(){
    // Select input field contents
    this.select();
    });

    ReplyDelete
  14. You don't need to call focus() - just call select().

    ReplyDelete
  15. Thanks. Here's an improved version:

    $("#myInputField").bind(
    'focus click',
    function(e){
    e.preventDefault();
    $(this).select();
    }
    );

    ReplyDelete
  16. Is there a reason this does not work on mobile safari? It seems to work on all other webkit browsers...

    ReplyDelete
  17. Just to expand on Brandon's code, I needed this for users to select embed code for a tube video where it highlights (selects) the embed code when clicking on the input field.. I used the following jQuery:

    $('#embed-code').click(function(){
    $(this).focus().select();
    });

    Here was my input field:



    If you are passing raw html to the input value from a script, make sure to run it through php's htmlspecialchars so it does not mess up your input.

    The comment box is not letting me paste some html, correct "input" if you use this code above.

    ReplyDelete
  18. If input more than one, basic function work on first element only. So you must use Live or On, like this :

    $("input[type=text]").live('click',function(){
    // Select field contents
    this.select();
    });

    Please make sure your jquery version should 1.3.2 for Live. because Live was depecreted for version after.

    ReplyDelete
  19. Just work in firefox...

    ReplyDelete
  20. This work for me!
    $('#myInputField').focus().select();

    JD

    ReplyDelete
  21. Like Brandon, this wasn't quite working for me at first, but following his tip worked great. Thanks for your post that got me there!

    Michael

    ReplyDelete
  22. Truly brilliant and simple! Thanks a lot - saved me so much time.

    ReplyDelete