Wednesday, June 23, 2010

How-to use ClientIDs in JavaScript

with their parent’s ID.


<div id="parent" runat="server">
<asp:TextBox ID="txtUsername" Runat="server" />
</div>

This isn’t really much of a problem when all you are working with is server-side code, but when you start tinkering with JavaScript, things become quite annoying and get an overall feeling of hackyness.

One solution, which I have used time-and-again, is to use a script block at the end of your page where you create a series of variables that contain the actual IDs. You then use these variables to reach the actual elements via JavaScript.

<script type="text/javascript">
var txtUsernameID = '<%= txtUsername.ClientID %>';
var txtPasswordID = '<%= txtPassword.ClientID %>';
</script>

This solution works fine, but it isn’t exactly pretty and it doesn’t weigh well on my conscience.

No comments:

About Me

Bangalore, Karnataka, India