Click and Highlight Text in a TextBox using jQuery

Here’s a simple script that highlights the Text in a TextBox using jQuery, when the user clicks inside it. This technique of highlighting text is useful in forms when there are frequent copy paste operations.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Click and Highlight Text</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#Text1").click(function() {
$(this).focus();
$(this).select();
});
});
</script>
</
head>
<
body>
<
input id="Text1" type="text" value="There is some text here"/>
</
body>
</
html>
image 

Here’s a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Ante said...

One of jQuery's cool features is nested function-calls. The code could be written as follows instead:

$(this).focus().select();

This avoids calling the jQuery-function (or $) twice as well as saving some bytes.