Sam
Sam

Reputation: 105

Referencing ASPX controls from an External JS file

I have a question. I have a aspx control (for e.g textbox). I reference it using document.getElementById('<%=textbox.ClientID%>').value. When I have the code in the same aspx file it works. But as soon reference it from an external file (example MyJSFunctions.js), I cannnot. I get an error saying "the object does not exist or it is null"

I have included the name of the js file like

I did this because I like having all my js functions in a seperate file nad doing this also reduces the load overhead.

Why is this happening? Can I accomplish the same using jquery?

Upvotes: 4

Views: 2330

Answers (2)

Grant Thomas
Grant Thomas

Reputation: 45083

You will need to parametise your Javascript to accept the desired argument, then pass the inline ASP.NET script within the server-side page or control as the value of such. This will allow the engine to render the inline code appropriately.

It happens because the server renders your pages (not in the sense of a browser rendering HTML, but rather the ASP.NET engine making transformations to turn your .NETified web mark-up into standard web mark-up) prior to pushing them down to the client - this will only happen for "registered" types, and that doesn't (and shouldn't) include Javascript files (although you can technically register items to handle, unless you have a bespoke module to handle compilation of inline scripting among Javascript, then it would err anyway.)

jQuery essentially being something of a Javascript framework, you're in the same boat with that, so to speak.

As an example, consider the following...

Your script file:

function doSomethingJavascripty(withThisClientID) {
    //do something with...
    document.getElementById(withThisClientID).value;
}

Your ASPX page:

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

<script type="text/javascript">
    //call your function when appropriate...
    doSomethingJavascripty('<%=textbox.ClientID%>');
</script>

Upvotes: 4

Mike Christensen
Mike Christensen

Reputation: 91618

One thing you could do is have the following Javascript code in your ASPX page:

var myTextbox = '<%=textbox.ClientID%>';

Then, in your external JS file (make sure this is after the above line), have:

document.getElementById(myTextbox).value

Another alternative is just hardcode in the ClientID into your code, but note you'll break it if you change the ID or parent container of that textbox control in the future.

Upvotes: 2

Related Questions