views:

1262

answers:

4

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?

A: 

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]);
Carter
A: 

Few ways-

  1. 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.

  2. 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/

Chetan Sastry
+2  A: 

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;";
brendan
A: 

Here's what I run into. I can use the <%= this.ClientID %> as long as the page has only one instance of the User Control. As soon as I add multiple instances, the ClientID will be the ID of the user control added last.

I assume that this is because the JS is rendered multiple times on the page and the variable is overwritten with a new value?

How would I solve this?