Clone the Value of a TextBox as the User Types in it using jQuery

I recently saw a question on the forums where a user wanted to clone the value of a textbox contents into another, as he typed in it. Here’s how to achieve this requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Clone the Value of a TextBox as the User Types in it</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#tb1").keyup(function() {
var txtClone = $(this).val();
$("#tb2").val(txtClone);
});
});
</script>
</
head>
<
body>
<
input id="tb1" type="text" />
<
input id="tb2" type="text" />
</
body>
</
html>



To do it an ASP.NET Page

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
<
title>Clone the Value of a TextBox as the User Types in it</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$('input[id$=tb1]').keyup(function() {
var txtClone = $(this).val();
$('input[id$=tb2]').val(txtClone);
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="tb1" runat="server" /><br />
<
asp:TextBox ID="tb2" runat="server" />
</
div>
</
form>
</
body>
</
html>

Observe how I am using ('input[id$=tb1]' in an ASP.NET page. Using this technique makes it easy to find a control in a MasterPage scenario.

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

No comments: