Reputation:
I have a host page that dynamically loads multiple instances of the same user control by assigning different IDs.
After the UC loads, I will need to use JS to get a reference to a textbox. For this, I need the User control Client ID. I do have access to the UC Client ID on the server side and can set a hidden form variable with this information. But I run into the problem of referencing this form variable from javascript as I need the UC client ID to be able to do so.
What's the best approach for this problem?
Upvotes: 2
Views: 3546
Reputation: 2870
If I understand correctly you can get access to the ID by throwing this in between some script tags on your page...
var controlClientId = '<%= control.ClientID %>';
Then just use controlClientId in your js.
EDIT: I'm not entirely clear on what the code on your end is doing, but I'm assuming you just new up some instances of that control in a loop and assign them a unique Id and add them? If this is the case, then I would run a loop in your codebehind to find all the controls and register them in a client array, or just do it as they are created.
ClientScript.RegisterArrayDeclaration("ControlIds", String.Concat("'", Control.ClientID, "'"))
Then you can do stuff like this in your Javascript...
for (var i = 0; i < ControlIds.length; i++) alert(ControlIds[i]);
Upvotes: 0
Reputation: 29976
One approach is to emit the js code server side. For example if you need to call a function on that textbox - simple example:
Say you have some javascript:
function ShowMeTheId(id)
{ alert(id); }
In code behind you can put something like this to call it from a button and pass in your textbox id :
MyButton.OnClientClick = "ShowMeTheId('" + MyUserControl.TextBox1.ClientID + "'); return false;";
Upvotes: 2
Reputation: 23803
Few ways-
Use css classes to reference your control from javascript. Caveat: getting elements by class name is slower than getting by id, especially if you are doing it often.
Instead of setting a form variable which, in turn, gets an obscure id, you can set a javascript variable in your aspx file using <%=userClient.ClientID%>
See this blog post for more ideas. http://blog.jagregory.com/2006/04/12/how-to-use-clientids-in-javascript-without-the-ugliness/
Upvotes: 0