Reference ASP.NET control by ID in JavaScript?

This post by Dave Ward might have what you’re looking for:

http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/

Excerpt from article:

Indeed there is. The better solution
is to use inline ASP.NET code to
inject the control’s ClientID
property:

$get('<%= TextBox1.ClientID %>')

Now the correct client element ID is
referenced, regardless of the
structure of the page and the nesting
level of the control. In my opinion,
the very slight performance cost of
this method is well worth it to make
your client scripting more resilient
to change.

And some sample code by Dave from the comment thread of that post:

<script>
  alert('TextBox1 has a value of: ' + $get('<%= TextBox1.ClientID %>').value);
</script>

The comment thread to the article I linked above has some good discussion as well.

Leave a Comment