Thursday, June 18, 2009

Accessing ASP.Net controls in JavaScript

If you have an ASP.Net control in your web-page with ID “aspCtrl” how do you access it in JavaScript?

One would think that document.GetElementByID(“aspCtrl”) would work. And it would in a very simple Asp.Net page. But the minute your control begins being put into other Asp.Net controls, you will find that the ID of your controls will be changed by the run-time before being sent to the client’s browser.

So how do you work around this?

Use the client id of the control – like so:
var ctrl1 = document.getElementById('<%=aspCtrl.ClientID%>').value;

So if you are familiar with UniqueId then you might be wondering what the difference is between UniqueID and ClientID? The difference is that ClientId is the value that would be assigned to the control’s ID attribute (which is why you use it in GetElementById). UniqueID, contains the fully qualified name for that control (which includes the names of all the controls that contain that element concatenated with weird symbols($) and all).

Now you know!

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.