Get clientid in user control from external javascript file

By : Giorgi
Source: Stackoverflow.com
Question!

I am developing a user control (ascx) in ASP.NET which uses javascript for manipulating controls. Currently the javascript code is inlined and uses <%= somecontrol.ClientID %> to get the control it needs.

I want to put the javascript file in external file but from external file I cannot use the above syntax for retrieving controls. I have read about possible solutions in this and this answers but the problem is that the user control can be placed multiple times on page. This means that the Controls array (mentioned in the answers) will be rendered several times with different items. As a result the script will not be able to retrieve the id it needs. If I put <%= ClientId %> in the name of array that holds items then I will have the same problem as I am trying to solve.

Any ideas?

By : Giorgi


Answers
Ok, a different approach, that I try to use a JavaScript-class style, and then initialize it for each control.

In the external javascript file, write your code as:

function oNameCls(ControlId1) {

    this.ControlId1 = ControlId1;

    this.DoYourWork1 = function() {
        // use the control id.
        // this.ControlId1
    }    
    this.DoYourWork2 = function() {
        // use the control id.
        // this.ControlId1
    }    

}

And on the control do the call like that.

<script language="Javascript" type="text/javascript">
    // init - create
    var <%=this.ClientID%>MyCls = new oNameCls(<%=Control1.ClientID%>);
    // do your work
    <%=this.ClientID%>MyCls.DoYourWork1();
</script>

Hope now help better.

By : Aristos


The way I solve this problem is to use CSS classes or place the controls within containers with known IDs and then traverse into the container's children to get the actual controls. For example:

<asp:TextBox ID="Something" runat="server" CssClass="mycontrol" ... />

Could be accessed via:

jQuery('.mycontrol');

Or:

<div id="ControlContainer">
    <asp:TextBox ID="Something" runat="server" ... />
</div>

Could be accessed via:

jQuery("#ControlContainer input[type='text']");

The only real problem with this approach is you're tying your code to specific markup on the page, which can be a hassle if the markup changes a lot.

By : Rudism


What about a hidden variable:

<input type="hidden" id="ClientId" value="<%=ClientId %>">

Then from your js:

$("#" + $("#ClientID").val())

Or, put the hash in:

<input type="hidden" id="ClientId" value="#<%=ClientId %>">

...

$($("#ClientID").val())


This video can help you solving your question :)
By: admin