Accessing ASP.NET Server Control Elements in Javascript

For a while I struggled with the idea of integrating ASP.NET pages with Javascript. After all, the IDs of the HTML elements inside server controls were all generated during runtime in ASP.NET… so how do you easily refer to them?

The answer is simpler than I thought. Each ASP.NET server control has a ClientID property that you can use to get the full ID string that will be rendered in the HTML output.

Suppose you have a textbox named txtName in your ASP.NET page. Up in the HEAD section of your ASPX markup, include this simple javascript block to access the HTML INPUT element that the TextBox server control encapsulates on the client:

<script type="text/javascript">

// Get my text box
var txtName = document.getElementById('<%=txtName.ClientID%>');

// Say hello!
alert('Hello, ' + txtName.value);


You can use this technique for all sorts of controls, including drop-down lists, buttons, radio buttons, checkboxes, etc.


Trackback URL:

Blog post currently doesn't have any comments.
Leave comment

 Security code


This web site uses Kentico CMS, the content management system for ASP.NET developers.