Reference a Dynamically Created Control

Wishing to reference an asp.net control (vb.net or c#) in JavaScript or jQuery how can I do this given that the ID is dynamically created?

I can’t just write

var fruitName = document.getElementById(‘tbxName’);

Or the jQuery equivalent of

Var fruitName = jQuery(‘#tbxName’);

Each asp.net control added to the page is assigned a unique reference ID composed from the module control and page or something.

Here’s textbox control

<asp:TextBox id=”tbxName” runat=”Server” />

with a typical page representation

Writing reusable modules and controls when it is rendered on the page it’s dynamic naming will be affected by such tie as it’s page content area.

Thus observing the construction in a test page and including this as per the query example below is unlikely to be valid in real use. Or even if used again within the same test website.

JQuery (‘#tbxName’).addClass(‘required’)

At the time of viewing the page the textbox’s ID is unknown.

Shown below is an example auto generated textbox field:

<input name="dnn$ctr429$Site$tbxName" value="Apples" maxlength="120" id="dnn_ctr429_Site_tbxName" required="" type="text">

In this example the ID tells us that its a DNN site, control number 429, with a module called site and the reference used for the field is tbxName.

Writing CSS, jQuery or JavaScript there are times when accessing the unique Id created for a control is desired.

Because the value is assigned dynamically access to the value also requires access to the dynamic value.

To do this we use the client Id value adding a reference to an asp.net (VB or C#) to one of the controls, using its id reference. For example reference a textbox.

<asp:TextBox id=”tbxName” runat=”Server” />

or a radio button

<asp:Radiobutton id=”cbxFruit” ResouceKey=”cbxFruit” />

<asp:Radiobutton id=”cbxVeg” ResouceKey=”cbxVeg” />

For a one-off reference we may choose to do something like

jquery("#<% = tbxName.ClientID %>").
  jquery("#<% = cbxFruit.ClientID %>").click(function(){
});

A variable could be set or a function called passing the value.

var vegName = ‘<% = tbxName.ClientID %>’;

This style of reference must be added within the page, not within a separate JavaScript file. In this case the reference won’t be found.

Don’t just add these to the footer without providing a check to ensure that the entry exists on the page. Otherwise an error relating to the unfound reference will be created.

The check will need to be in the server code, either c# or vb.net.

I prefer to include such references within the module development. It is then known what entries have been added to the page.

Create a variable for the dynamic reference to the control which is set at runtime, with a server conditional implementation to avoid errors.