Referencing server controls from Javascript
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.
Revision number 4, Monday, September 22, 2008 8:41:56 PM by mbanavige
You must Login to comment.
|
Fri, Sep 26, 2008 2:24 AM
by uniquesaiful
|
Nice article
|
|
Sun, Sep 28, 2008 12:13 PM
by JohnAClee
|
Nice simple article. A lot of developers seem to shy away from javascript, but it is this easy to modify a client page without a postback. Reducing server traffic and meaning the client doesn't have to wait for the server round trip.
|
|
Thu, Oct 2, 2008 10:21 PM
by tymberwyld
|
This is not a very good way of doing it and it only works when you JavaScript is embedded in your ASPX Source. If you truly want to take advantage of JS nowadays, you have the JS in a seperate file so you can debug it. However, how do you get the server control reference? Easy, there's a little pattern I like to call, the "Script Registration" pattern. Basically, this is a function I add to any page that needs to register some server-side controls for use client-side: In your code behind of the Page. This also takes into account AsyncPostBacks that occur through an UpdatePanel: private void RegisterScripts()
{ System.Text.StringBuilder script = new System.Text.StringBuilder(); script.AppendFormat("ver txtFirstName = $get('{0}');\n", this.txtFirstName.ClientID); script.AppendFormat("ver txtLastName = $get('{0}');\n", this.txtLastName.ClientID); string scriptKey = this.ClientID; ScriptManager sm = ScriptManager.GetCurrent(this); if (sm != null && sm.IsInAsyncPostBack) ScriptManager.RegisterStartupScript(this, this.GetType(), scriptKey, script.ToString(), true); else Page.ClientScript.RegisterStartupScript(this.GetType(), scriptKey, script.ToString(), true);
} Now, in your JavaScript there is never a need to use "getElementById" ever again! function doSomething()
{ txtFirstName.value = "My First"; txtLastName.value = "My Last";
}
|
|
Thu, Oct 2, 2008 10:22 PM
by tymberwyld
|
Wow, this comment thing REALLY screws up all the formatting! Sorry about that guys!
|
|
Thu, Oct 23, 2008 10:34 AM
by priyasadiwala
|
Good one.. For beginners in Javascript.
|
|
Fri, Dec 26, 2008 8:42 AM
by sirdneo
|
Simple and nice. Good Effort
|
|
Sat, Mar 28, 2009 2:39 AM
by vrpmca
|
Thanks tymberwyld..
|
|
Sat, Jan 2, 2010 12:19 PM
by lianaent
|
THANK YOU TYMBERWYID!!!
|
|
Sat, Jan 2, 2010 4:02 PM
by lianaent
|
Hmmm, I have to take that back! This doesn't seem to work when there are postbacks, or maybe it's because my controls are inside an update panel and I'm trying to change their contents dynamically. For now, I have to go back to $get('ctl00_lblDesc').innerHTML = txt; Any suggestions?
|
|
Sat, Jan 2, 2010 4:31 PM
by lianaent
|
Maybe I should clarify. I'm trying to update text (Label) inside a ModalPopupExtender which is inside an UpdatePanel. Using tymberwyid's technique works great the first time you open the popup, which was why I was excited. But when you close it and reopen it, no dice. I can look at my label text with an alert and it's there, but on the next line when I do popup.show() the label is blank. go figure...
|