In this article we will show you how to reference server side controls from JavaScript code (A server control is a control that has a runat="server" attribute).
Generally, every server control has an ID on the server side. One common problem when accessing the server side controls from JavaScript is that developers assume that the control's server side ID can be used directly in JavaScript code to reference the rendered control on the client side. This is incorrect assumption.
The client side ID of the rendered control is not always the same as the ID on the server side. If you have placed the server side control inside another control which implements the INamingContainer marker Interface, the runtime will change the controls client side ID to enforce the uniqueness of that ID in the rendered html document. You can get the resulting client side ID through the controls ClientID property.
Note: You will notice this behavior when you start working with MasterPages or when you place the control inside GridView control or any other control that implements INamingContainer Marker Interface.
The following example will show you how to reference the Input control using its ClientID property:
<script language="javascript" type="text/javascript">
function incrementValue() {
var txtToIncr = document.getElementById('<%= txtToIncr.ClientID %>');
var CurrentValue = 0;
if (txtToIncr.value != '')
CurrentValue = parseInt(txtToIncr.value);
txtToIncr.value = CurrentValue + 1;
}
</script>
<div>
<input id="txtToIncr" type="text" runat="server" value="0" />
<asp:Button ID="BtnIncrement" runat="server" Text="Increment From Client Side" UseSubmitBehavior="false"
OnClientClick=" return incrementValue();" />
<asp:Button ID="BtnIncrementFromServer" runat="server" Text="Increment From Server Side" />
</div>
Code Behind:
Protected Sub BtnIncrementServer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnIncrementServer.Click
Dim Currentvalue As Integer = 0
If (txtToIncr.Value <> "") Then
Currentvalue = Integer.Parse(txtToIncr.Value)
End If
txtToIncr.Value = Currentvalue + 1
End Sub
In the example, there are two TextBox controls. The first one "BtnIncrement" can be used to change the Input control value via JavaScript code and the other control "BtnIncrementFromServer" is used to change the Input value from server side code.