Thursday, 2 May 2013

jQuery with ASP.NET – clone textbox example

Step 1: Create a Master Page (MasterPage.master) and add a reference to the jQuery Library. Now create a folder called ‘Scripts’ and download the latest jQuery library into this folder. Now add references to any CSS files, if any. Create a separate folder to store all CSS and images files. You should always make it a habit to keep your resources in separate folders for better maintainability. The code should look similar to the following:
Step 2: Now create a Content Page called ‘Default.aspx’ and add two TextBox controls to this page as shown below:
Step 3: Now in the ‘Scripts’ folder, create a textboxclone.js file and add the following code in it.
Using the code shown above, as the user types in the first TextBox, we retrieve the value of the first TextBox and set it to the value of the second TextBox. Note: Since we are capturing the keyup event, whenever the user pastes text in the first textbox using Ctrl+v, the contents are cloned into the second textbox, This is however not true when the user right clicks the textbox and chooses paste from the context menu
The last step is to reference this JavaScript file (textboxclone.js) in your Content Page as shown below:
You must be wondering why did we add a link to the textboxclone.js from a Content page rather than doing it from a Master Page. The reason is, if we had referenced the textboxclone.js file in the MasterPage directly, the code would be downloaded for every content page, even if it was not needed. Referencing it from a Content Page makes sure that the resource is used only when this content page is requested. That’s it. Run the code and you will see the textbox text cloning in action.

No comments:

Post a Comment