Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


You can change to ClienIDMode property of the control to 'Static' that will result the same ID that you give the control in the .NET code.

<asp:TextBox ID="TextBox1" ClientIDMode="Static" runat="server"></asp:TextBox> 

will result:

<input name="ctl00$MainContent$TextBox1" type="text" id="TextBox1"> 

so you have the same ID.


Couple of thoughts on this:

1) I've had a lot of luck getting elements by css class instead of id because asp.net ids are not reliable as you stated. I use this function and it performs reasonably well:

function getElementsByClass(searchClass,node,tag) {
 var classElements = new Array();
 if ( node == null )
    {
        node = document;
    }

 if ( tag == null )
    {
        tag = '*';
    }

 var els = node.getElementsByTagName(tag);
 var elsLen = els.length;
 var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");

 for (i = 0, j = 0; i < elsLen; i++) 
    {
        if ( pattern.test(els[i].className) ) 
            {
                classElements[j] = els[i];
                j++;
            }
      }
 return classElements;
}

2) jQuery helps here alot. Using jQuery you can reliably get elements where the id ends with a certain string. While this is not "the" reason to use jQuery it's definitely a plus.

3) This will be fixed in asp.net 4.0 so hang in there :-) http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx