Where does ASP.Net get its rendered IDs from?
I inherited a project with some nasty JavaScript that relies on hardcoded object IDs.
those. There are many places where he does this kind of thing.
var magazine = document.getElementById('repModuleDisplay__ctl3_chkCats_0');
When the page is rendered in my UAT environment the HTML looks like this and everything works fine.
<input id="repModuleDisplay__ctl3_chkCats_0"
type="checkbox" name="repModuleDisplay:_ctl3:chkCats:0"
... etc
However, when I put it in my production environment, the HTML is suddenly destroyed like this:
<input id="repModuleDisplay_ctl03_chkCats_0"
type="checkbox" name="repModuleDisplay$ctl03$chkCats$0"
... etc
The difference in IDs means JavaScript cannot find the element and does not work.
In an ideal world, I would ditch the faulty JavaScript and do it right again, but for a quick fix, I would like to know what is causing the rendering difference between the two environments.
Does anyone have any ideas?
Thanks, Neil
a source to share
The quickest and simplest fix I can think of - and it's probably not very fast or easy if the code is all over the place - is to use the actual property ClientID
of the control instead of trying to guess what the generated id might be:
// i've assumed that the control is named chkCats
var magazine = document.getElementById('<%= chkCats.ClientID %>');
a source to share
This link gives you a quick rundown of how ASP.NET creates IDs, and all the other posters have recommended the correct solution for using the ClientID of the client.
If you want to avoid ASP style tags, then another option is to release some js to your page during PreRender:
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("var myTextBox = document.getElementById('{0}');", MyTextBox.ClientID));
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "myElementDefinitions"))
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myElementDefinitions", sb.ToString());
and then in your javascript code, you just reference it named myTextBox. This option may not suit you, depending on your code and how often you use ASP tags to reference the same control ID.
a source to share