jQuery + Javascript: How to Select all Text in a Textbox

I have a nice little inline editing function attached to one of my administrative pages which basically lists a whole lot of tag names currently saved on the system.

When you click on the tag name, it gets replaced by a textbox containing the name, allowing you to edit and then save your changes.

In order to make the experience a little more streamlined, I wanted to set it up so that when clicking on the tag name the text box should appear directly in its place, with all the characters in the textbox highlighted (i.e. selected) and with browser focus firmly on the box.

Achieving this turns out to be pretty simple.

Basically, plain old vanilla JavaScript already gives us the functionality to focus on an input element as well as select all characters in that element. So, we stuff that into its own little function:

function selectAllText(textbox) 
 
{
 
  textbox.focus();
 
  textbox.select();
 
}

We then attach this function to the moment the textbox appears in place of the original label, binding it to the click event of the label element:

 
$('#tagname').click(function(){
 
$(this).hide();
 
$('#textboxtag').show();
 
selectAllText($('#textboxtag'));
 
});

There, all done! (Now wasn’t that nice and simple stuff?)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , , . Bookmark the permalink.
  • http://www.zicocn.com/ China Electronics Wholesale

    thanks for your share, i need this

blog comments powered by Disqus