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>
- var intFirstNo = document.getElementById("<%= txtFirstNo.ClientID %>").value;
- var intFirstNo = document.getElementById("txtFirstNo").value;
Just copy the above sample in a webform and try it yourself. Please leave your valuable comment which improves every article.
Happy coding!

Santhakumar MunuswamyPosted Dec 29, 2015, 10:45 AM
Thanks for sharing
Sibeesh VenuPosted Dec 29, 2015, 6:48 AM
Nice Share