5

How can I use server-side script in an external js file to grab a reference to a dom element?

The following works as intended when used as inline-script, but is returning null when I move this to an external js file.

$("#<%= gridResults.ClientID %>");
Jeremy
  • 9,023
  • 20
  • 57
  • 69
  • 3
    See http://stackoverflow.com/questions/844970/is-there-a-better-way-to-get-clientids-into-external-js-files and http://stackoverflow.com/questions/1232465/how-to-use-jquery-select-element-by-id-and-asp-net-without-putting-ctl00-everyw/1232498#1232498 for a couple of general solutions to this. See http://stackoverflow.com/questions/497802/how-to-stop-asp-net-from-changing-ids-in-order-to-use-jquery/497872#497872 for a jQuery solution. – Crescent Fresh Nov 19 '09 at 15:10

4 Answers4

11

You'll need to have an inline script block that creates a JavaScript variable. This block should be added before your external JavaScript file. Once you do this, you can reference that variable in your external JavaScript file.

<script type="text/javascript">
    var grid = $("#<%= gridResults.ClientID %>");
</script>

<script type="text/javascript" src="path/to/my.js"></script>
Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
1

You can't put #<%= gridResults.ClientID %>, because the gridresults.ClientID is specific to that asp.net page.

You could do:

<stript src="yourfile" type="text/javascript"> <!--link to external js file-->

<script type="text/javascript">
  var grid = $("#<%= gridResults.ClientID %>");

  yourfunction (grid);

</script>
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
1

If you but a unique class on the grid using the CssClass property, you should be able to access the grid without having to know what it's clientID is.

Chris
  • 6,272
  • 9
  • 35
  • 57
0

What you want to happen cannot. The external javascript file is not parsed by the ASP.NET page's code behind, so the functionality of ASP.NET is not available to it.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90