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

1 comment:

  1. 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.

    ReplyDelete