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 (when onfocus event is fired basically).

Selecting a text in your inputbox on focus is easy and actually 3 lines of jQuery code, but it add a nice usability touch to your site. This “select all” behavior is default in browser when you browse through form fields using TAB key, but when you click on to the input text field it does not behave like that.

jQuery code to select text inside an input field on user click or focus:

$("#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();
});

TIP:
Change the selector in the second example and get this behavior to password fields, textarea fields, etc.

Also we can add a little spice into our code and only select the contents of our text field or textarea if it has not been changed from its default original value.

// Let's add it to textarea this time
$("textarea").focus(function(){
    // Check for the change
    if(this.value == this.defaultValue){
        this.select();
    }
});

The code above selects all text content of textareas if and only if it’s value has changed from the original one. This behavior would probably be more useful on input fields :)