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.