February 2011 - Posts

Select a textbox’s text on focus using jQuery
01 February 11 03:23 AM | Scott Mitchell | 2 comment(s)

A fellow ASP.NET developer asked me today how he could have the text in a TextBox control automatically selected whenever the TextBox received focus.

In short, whenever any textbox on the page receives focus you want to call its select() function. (The JavaScript select() function is the function that actually selects the textbox’s text, if any.) Implementing this functionality requires just one line of JavaScript code, thanks to jQuery:

$("input[type=text]").focus(function() { $(this).select(); });

In English, the above line of code says, “For any <input> element with a type=”text” attribute, whenever it is focused call it’s select() function.” If you only wanted certain textboxes on the page to auto-select their text on focus you’d update the selector syntax accordingly. For example, the following modification only auto-selects the text for those textboxes that use a CSS class named autoselect:

$("input[type=text].autoselect").focus(function() { $(this).select(); });

That’s all there is to it! You can view the complete script and try a working demo at http://jsfiddle.net/ScottOnWriting/Kq7A4/2/

One final comment: if one or more of the textboxes you want to auto-select exist within an UpdatePanel control then consider using jQuery’s live() function. The live() function maintains the event bindings even when the HTML is regenerated due to a partial page postback; for more information, see my article – Rebinding Client-Side Events After a Partial Page Postback. For more information on jQuery, see Using jQuery with ASP.NET.

EDIT [2011-03-29]: To get this to work in Safari / Chrome you will need to add a mouseup event handler and disable the default event, as the onmouseup event is causing the textbox to be unselected. For more details, see this Stackoverflow post: Selecting text on focus using jQuery not working in Safari and Chrome.

$("input[type=text].autoselect").focus(
    function() { 
         $(this).select(); 
    }
 )
 .mouseup(
    function(e) {
        e.preventDefault();
    }
 );
    
Filed under:
More Posts

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.