Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get asp.net client id at external javascript file

When I use embedded javascript functions I can get client id of elements with this code:

document.getElementById('<%=buttonXXX.ClientID%>' )

But now I am using external javascript file for caching and faster rendering and this code does not work any more for getting client id's of elements, it gives error.

How can I get client id's of elements at external javascript file using asp.net 2.0 , netframework 3.5 , c# , iis 7.5

like image 829
MonsterMMORPG Avatar asked Oct 02 '10 13:10

MonsterMMORPG


People also ask

How do I reference an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

What is <% in JS?

The server tag <%= %> is used to enter code that is processed on the server. You cannot use <%= someObject. ClientID %> in an external js file because the server tag is an asp.net thing and js doesn't know what this is.

What is ClientID in JavaScript?

The ClientID value is often used to access the HTML element in client script by using the document.getElementById method.

What is jQuery ClientID?

To find any ASP.NET Control in jQuery, we use Client ID property to get the correct ID of the rendered control. For example, to find an ASP.NET textbox with ID "txtName", a familiar jQuery syntax is, $('<%= txtName. ClientID %>').


1 Answers

I can suggest 2 ways.

First way

define your variables before call the javascript, inside the .aspx file that can be compiled.

var ButtonXXXID = <%=buttonXXX.ClientID%>
// and now include your javascript and use the variable ButtonXXXID

Second way

in the external javascript file, write your code as:

function oNameCls(ControlId1) {

    this.ControlId1 = ControlId1;

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

And call your actions like.

<script>
    // init - create
    var <%=this.ClientID%>MyCls = new oNameCls('<%=Control1.ClientID%>');
    // do your work
    <%=this.ClientID%>MyCls.DoYourWork1();
</script>

calling the action this way you prevent overwrite one action from one control with the same action from other controls on the same page.

like image 152
Aristos Avatar answered Sep 28 '22 05:09

Aristos