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();