tag:blogger.com,1999:blog-3930375442497799514.post-21379480584432786522008-07-31T13:15:00.000-07:002008-07-31T13:41:20.631-07:002008-07-31T13:41:20.631-07:00ASP.NET GetElementById for server controlThis 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.<br/><br/><b>Deal with it at the server</b><br/>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:
<blockquote style="font-family: courier;">txtName.UniqueID.Replace(":","_")</blockquote>
You can then build your JavaScript like this:
<blockquote style="font-family: courier;">ClientScript.RegisterStartupScript(this.getType(),<br/>"blah","alert('"<br/>+ txtName.UniqueID.Replace(":","_")<br/>+ "');",true);</blockquote>
<b>Or, Deal with it at the client</b><br/>
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.<br/><br/>Here's how I do it...<br/>
<blockquote><pre style="font-family: courier;">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;
}</pre></blockquote><br/>You can call it like this:<blockquote style="font-family:courier">var x = GetElementByIdEndsWith("input","txtName");</blockquote>Tom Puleohttp://www.blogger.com/profile/10697521511530638404noreply@blogger.com2