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(),Or, Deal with it at the client
"blah","alert('"
+ txtName.UniqueID.Replace(":","_")
+ "');",true);
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:
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
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.
Post a Comment