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...

 

4 Comments

Comments have been disabled for this content.