IntroductionIn this article, I'm going to explain how to Get and Set value to Server control in asp.net within JQuery Code.We are all know Get and Set in Server side code, but when you use Jquery how to achieve that.I know most of people know about it as Jquery is very popular browser JavaScript framework. I believe jquery as framework because it’s a single file which has lots of functionality. For this I am going to take one simple example asp.net page which contain two textboxes txtName and txtCopyName and button called copyname. On click of that button it will get the value from txtName textbox and set value of another box. So following is HTML for this. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Experiment.Index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server" />
<asp:TextBox ID="txtCopyName" runat="server"/>
<asp:button ID="btnCopyName" runat="server" Text="Copy" OnClientClick="javascript:CopyName();return false;"/>
</div>
</form>
</body>
</html>As you can see in following code there are two textbox and one button which will call JavaScript function called to CopyName to copy text from one textbox from another textbox.Now we are going to use the Jquery for this. So first we need to include Jquery script file to accomplish the task. So I am going link that jquery.js file in my header section like following. <head >
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>Now it’s time to write query code. Here I have used val function to set and get value for the element. Following is the code for CopyName function. function CopyName() {
var name = $("#<%=txtName.ClientID%>").val(); //get value
$("#<%=txtCopyName.ClientID%>").val(name); //set value
return false;
}Here I have used val function of jquery to set and get value. As you can see in the above code, In first statement I have get value in name variable and in another statement it was set to txtCopy textbox. Some people might argue why you have used that ClientID but it’s a good practice to have that because when you use multiple user controls your id and client id will be different. From this I have came to know that there are lots of people still there who does not basic Jquery things so in future I am going to post more post on jquery basics.That’s it. Hope you like it |