Sometimes, we have a situation to access the server side ASP.NET controls and its values using client side script like JavaScript. In this post I’m going to explain how to do that with a simple example.
A word about Client ID
As all of us know server side controls are submitted and processed by the ASP.NET engine, which emits the respective HTML to the browser. At that time the ASP.NET engine takes the server controls and provide ID (which can be varied across ASP.NET versions) for it.
Consider the following example, which has 3 text boxes, entered values in first 2 text boxes when the user clicks the button then JavaScript function called which will add the values and put it in 3rd text box. These controls are Server controls.
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
- <title></title>
- <script type="text/javascript">
- function Add()
- {
- var intFirstNo = document.getElementById("<%= txtFirstNo.ClientID %>")
- .value;
- var intSecondNo = document.getElementById("<%= txtSecondNo.ClientID %>")
- .value;
- var intResult = parseInt(intFirstNo) + parseInt(intSecondNo);
- document.getElementById("<%= txtResult.ClientID %>")
- .value = intResult;
- }
- </script>
- </head>
-
- <body>
- <form id="form1" runat="server">
- <table>
- <tr>
- <td> Enter First Number: </td>
- <td>
- <asp:textbox clientidmode="Predictable" id="txtFirstNo" runat="server"></asp:textbox>
- </td>
- </tr>
- <tr>
- <td> Enter Second Numer: </td>
- <td>
- <asp:textbox id="txtSecondNo" runat="server"></asp:textbox>
- </td>
- </tr>
- <tr>
- <td> Addition is: </td>
- <td>
- <asp:textbox id="txtResult" runat="server"></asp:textbox>
- </td>
- </tr>
- <tr>
- <td align="center" colspan="2">
- <asp:button id="btnResult" onclientclick="Add(); return false;" runat="server" text="Calculate"> </asp:button>
- </td>
- </tr>
- </table>
- </form>
- </body>
-
- </html>
Consider this JavaScript line:
- var intFirstNo = document.getElementById("<%= txtFirstNo.ClientID %>").value;
When the above line is read by the ASP.NET engine, it will search the Server control ID “txtFirstNo” and get the respective client ID, which has been assigned by ASP.NET engine. In other words, ASP.NET get the Client ID for that Server control “txtFirstNo” and substitute there in between the double quotes. As a result when viewing the view source of the page we can read the above one as follows:
- var intFirstNo = document.getElementById("txtFirstNo").value;
We also return false (in line no 42) after calling the JavaScript function "Add" to avoid the postback when we click the button.
Just copy the above sample in a webform and try it yourself. Please leave your valuable comment which improves every article.
Happy coding!