Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 366, trackbacks - 0

My Links

News

Archives

Image Galleries

Accessing Controls from ASPX to External JavaScript file

This example shows the basic way on how to access control from external javascript file (.js). Normally, we use the following line below when accessing control within our JavaScript method in the page.

document.getElementById('<%= TextBox1.ClientID %>');

AFAIK, Using  Inline expression like <% %> will not work within external  js files. As a workaround we can pass the id of the control (eg. TextBox) to the funciton as a parameter instead like:

External JS file:

 

function GetControlValue(obj)

{

   var box =  document.getElementById(obj);

   alert(box.value); // returns the value "Hello ASPNET"

}

ASPX:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Untitled Page</title>

<script src="JScript.js" type="text/javascript"></script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:TextBox ID="TextBox1" Text="Hello ASPNET" runat="server" />

        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="GetControlValue('TextBox1');" />

    </div>

    </form>

</body>

</html>

 

As you notice, we passed the ID of TextBox control which is "TextBox1" to the Javascript function and get the value to perform certain actions or conditions based on the value.

Print | posted on Tuesday, August 18, 2009 10:10 PM |

Feedback

Gravatar

# Accessing Controls from ASPX to External JavaScript file

Thanks for the sharing. That's really helpful.
8/18/2009 11:55 PM | MCSE Training
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: