Thursday, July 31, 2008

ASP.NET GetElementById for server control

This comes up a lot. You have a server control with an id like "txtName" and you need to reference that with Javascript, but when the page renders, if that textbox is within another server control, the id will change to something like "ct100$something$txtName". There are two ways to deal with this.

Deal with it at the server
If you're creating the JavaScript in the code-behind on the fly, then you can use the txtName.UniqueId, but sometime's there are colons in it that need to be underscores, so you can get the id like this:
txtName.UniqueID.Replace(":","_")
You can then build your JavaScript like this:
ClientScript.RegisterStartupScript(this.getType(),
"blah","alert('"
+ txtName.UniqueID.Replace(":","_")
+ "');",true);
Or, Deal with it at the client
Sometimes you need to have your JavaScript pre-written, like in a .js file. So, to find the control that has the id you want, what you really need to do is find the control who's id ends with the thing you're looking for.

Here's how I do it...
function GetElementByIdEndsWith(tagName,endsWith)
{
    var elements =
             document.getElementsByTagName(tagName);
    
    for(var i = 0; i < elements.length; i++)
    {
        if (elements[i].id.endsWith(endsWith))
        {
            return elements[i];
        }
    }
    
    return null;
}

String.prototype.endsWith = function(txt,ignoreCase)
{
    var rgx;

 if(ignoreCase)
 {
  rgx = new RegExp(txt+"$","i");
 }
 else
 {
  rgx = new RegExp(txt+"$");
 }

 return this.match(rgx)!=null;       
}

You can call it like this:
var x = GetElementByIdEndsWith("input","txtName");

2 comments:

technicalganesh said...

You can use the the ClientId property dynamically to get ClientId of the Control

Example:
document.getElementById("< % = txtUserId.ClientID % > ")
(remove the spaces) in the string within the quotation mark)

It works fine..
Ganesh Kumar

Tom Puleo said...

You know, it's funny. With all there is to know about ASP.NET, somehow I've never noticed that property! Thanks. That's great.