12 December 2007

ASP.NET Control IDs and jQuery

I'm using jQuery a lot more for DOM manipulation, UI sugar and general lessening of javascript drudgery. In an aspx page, referencing a control using js is a pain because of how ASP.NET munges the control name. For example, "ddlDate" becomes something like "ctl00_ddlDate." I found lots of articles about this and various approaches, but they all seemed a little too involved or fragile.

The good news is that the original control name always seems to be preserved at the end of the control id ("always" -- I hope that's correct and so far it's been working). So by using jQuery's  select[id$=  syntax, here is a really simple way to handle this:


<script language="javascript" src="Images/jquery-1.2.1.pack.js"></script>

<script language="javascript">

  $(document).ready(function(){

    var ddlDate = $("select[id$='ddDateName']");

    var txtStart = $("input[id$='txtDateStart']");

    var txtEnd = $("input[id$='txtDateEnd']")

 etc...

No comments: