0

How to use jQuery in external javascript file in ASP.NET?

This is my code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="~/Javascript/Javascript.js" runat="server"></script>
    <script src="~/Javascript/jquery-2.1.1.js"></script>
</head>

But in Javascript.js file, I can't use jQuery selector $(). When I use it doesn't work.

Javascript.js:

$(document).ready(function () { 
  alert('Hello'); 
});

This code doesn't work. Also IntelliSense doesn't work in Javascript.js.

1 Answer 1

2

You have to include jQuery before Javascript.js

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="~/Javascript/jquery-2.1.1.js"></script>
    <script src="~/Javascript/Javascript.js" runat="server"></script>
</head>

You said you have these errors in your developer console:

Failed to load resource: the server responded with a status of 404 (Not Found) localhost:46316/~/Javascript/Javascript.js 
Failed to load resource: the server responded with a status of 404 (Not Found) localhost:46316/~/Javascript/jquery-2.1.1.js 
Uncaught TypeError: undefined is not a function

You can fix these by setting the paths to your files correctly:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="/Javascript/jquery-2.1.1.js"></script>
    <script src="/Javascript/Javascript.js" runat="server"></script>
</head>

Make IntelliSense work by putting this line of code to Javascript.js (as you realized yourself):

/// <reference path="jquery-2.1.1.js" />

Read the documentation of IntelliSense features and reference directives in here: http://msdn.microsoft.com/en-us/library/bb385682.aspx#Features

Sign up to request clarification or add additional context in comments.

12 Comments

For ex, this code doesn't work. Also intellisense doesn't work $(document).ready(function () { alert('Hello'); });
Do you see any errors in the console of your developer tools (F12)?
Yes, there are errors, but I don't thik there must be error. I have used jquery in external javascript file in DreamVeawer but it doesn't in ASP.NET
Could you paste in the error you have there? Are you sure you have the relative paths to those files set correctly? You can drag&drop the files to <head> directly from Solution Explorer.
These are Chrome errors: Failed to load resource: the server responded with a status of 404 (Not Found) localhost:46316/~/Javascript/Javascript.js Failed to load resource: the server responded with a status of 404 (Not Found) localhost:46316/~/Javascript/jquery-2.1.1.js Uncaught TypeError: undefined is not a function
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.