Acessing ASP.NET Controls in Javascript: Best Practices

I try to spend as much time as possible on asp.net blogs and forums. I have observed many members posting part of their code on http://forums.asp.net to get the solution about the problem they are facing. One of the worst practices I have seen on forums is to use static control IDs in client script while writing javascript (I think they are getting that from ViewSource of the Page).

Static ID of the control used on asp.net page with master page looks somthing like:


ctl00_ContentPlaceHolder1_txtEmployeeName

which consists of whole control hierarchy from Master Page, ContentPlaceHolder on Master Page and finally textbox control. Here what we are interested in is only txtEmployeeName. Most of developers who are new to javascript just write following statement to get txtEmployeeName in javascript:


document.getElementById('ctl00_ContentPlaceHolder1_txtEmployeeName'); //Wrong way to access element


This works as well. But what if you or someone changes ID of any control in whole control hierarchy (e.g. ctl00_ContentPlaceHolder1_txtEmployeeName) or the whole control heirarchy itself changes (You put TextBox inside UserControl or AjaxControlToolKit Tab Container). The above statement will throw javascript error.

The better way to access any element on page within javascript is to use ClientID property of that control. Like:


document.getElementById("<%=txtEmployeeName.ClientID%>");  //Will always work


This will always work even if you change name of any control in control hierarchy or change control hierarchy itself.

Hope this helps...

 

Published Saturday, November 28, 2009 8:13 AM by chintanpshah

Comments

# re: Acessing ASP.NET Controls in Javascript: Best Practices

Friday, May 28, 2010 8:22 AM by Kaspars

What if i want to put all JavaScript in external file (.js). How can i get field by its ID from external JS file?

# re: Acessing ASP.NET Controls in Javascript: Best Practices

Wednesday, June 23, 2010 3:31 AM by chintanpshah

You can declare variable in aspx page. Like:

var txtEmployeeName = document.getElementById("<%=txtEmployeeName.ClientID%>");

and use txtEmployeeName variable in external javascript file.

To get intellisense of the variables declared in aspx file, you can use following:\

/// <reference path="../Admin/Test.Master"/>

# re: Acessing ASP.NET Controls in Javascript: Best Practices

Wednesday, June 30, 2010 12:20 PM by Sabby62

Thanks for this post.

# re: Acessing ASP.NET Controls in Javascript: Best Practices

Tuesday, March 27, 2012 7:40 AM by Brandon

Wonderful post. I learned many interesting things. Thank you)

Leave a Comment

(required) 
(required) 
(optional)
(required)