Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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.

 

Technorati Tags: ,,
Posted on Tuesday, August 18, 2009 10:10 PM ASP.NET , JavaScript , Tips&Tricks | Back to top


Comments on this post: Accessing Controls from ASPX to External JavaScript file

# Accessing Controls from ASPX to External JavaScript file
Requesting Gravatar...
Thanks for the sharing. That's really helpful.
Left by MCSE Training on Aug 18, 2009 11:55 PM

# re: Accessing Controls from ASPX to External JavaScript file
Requesting Gravatar...
does this hold valid in case of content page too?? And that too involving update panels? any ideas..but good post anyways
Left by suresh beniwal on Feb 02, 2010 6:10 PM

# re: Accessing Controls from ASPX to External JavaScript file
Requesting Gravatar...
Oops.. Guess I am late here in this post.

I am a junior Cisco CCNA networking trainer but interested to know how this code works...

Are we calling the JavaScript function GetControlValue() from aspx and passing the TextBox object when a click event happens in the Button?

GetControlValue('TextBox1')

Left by CCNA Chennai on Aug 13, 2012 10:03 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net