Link to home
Start Free TrialLog in
Avatar of jabcoco
jabcocoFlag for Canada

asked on

Using <%= myCtrl.ClientID %> outside of the aspx page in javascript function?

I have a page Default.aspx and i have a lots of of JavaScript stuff with variable using <%= myCtrl.ClientID %>.

It's works fine if all javascript are inside the aspx page, but is there a way to put all javascript in a separate file "ex: Default.aspx.js" and continue using <% = %> statement?

Thanks
Avatar of prairiedog
prairiedog
Flag of United States of America image

As long as you include the .js file in the aspx page header, it should work.
I don't think that works.
Best way is passing your <%= myCrtl.ClientID %> as a parameter of your function.
It seems that the autor is using <%= myCrtl.ClientID %>, and everything is fine with it now. The author does not want to have all JavaScript code embeded in the aspx page, so an included .js file shuld work as the embedded JavaScript code as long as the .js file is linked in the aspx page's <head> section.
Avatar of jabcoco

ASKER

prairiedog, don't seem to work..... if i put the function direct in my page it works fine but when the function is into a .js file... it's not working..
here is my code example
JavaScriptTest.aspx
---------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JavaScriptTest.aspx.cs" Inherits="JavaScriptTest" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="JavaScriptTest.aspx.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="showLabelInnerHtml();return false;" />
        <asp:Label ID="Label1" runat="server" Text="My Label Text"></asp:Label>
    </div>
    </form>
</body>
</html>
 
JavaScriptTest.aspx.js
-----------------------
function showLabelInnerHtml() {
    var lblID = '<%= Label1.ClientID %>';
    alert(lblID);
    alert(document.getElementById(lblID).innerHTML);
}

Open in new window

If you use .js file, you need to use the actual control ID, in your case "Label1", instead of "Label1.ClientID".
 
function showLabelInnerHtml() {
    var lblID = 'Label1';
    alert(lblID);
    alert(document.getElementById(lblID).innerHTML);
}
ASKER CERTIFIED SOLUTION
Avatar of prairiedog
prairiedog
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jabcoco

ASKER

Thanks