0

I have a simple javascript function

function SayTest() {
    alert("test");
}

I include the javascript file in my MVC 4 view

<script type="javascript" src="~/Scripts/MyScripts/MyScript.js"></script>

and call the SayTest function from within my view

<script type="text/javascript">
    $(document).ready(function () {
        $("#myBtn").click(function () {
            SayTest();
        });
    });
</script>

I'm getting an undefined function error. This is driving me nuts. If the js file was included and the function is define, why do I get an undefined function error?

6
  • 1
    Are you sure the script path is correct ? Commented Jul 16, 2013 at 6:04
  • your MyScript.js is not loaded. Commented Jul 16, 2013 at 6:05
  • MVC 4? If yes , you have to add the Bundle in BundleConfig.cs (RegisterBundles method) Commented Jul 16, 2013 at 6:08
  • Bring up Fiddler (or your favorite dev tools) and see if the script if being loaded (make sure you CTRL+F5 to disregard the cache). Commented Jul 16, 2013 at 6:09
  • Actually your jquery is not loaded yet just load jquer before you invoke the script Commented Jul 16, 2013 at 6:14

2 Answers 2

3

Try using :

<script type="text/javascript" src="~/Scripts/MyScripts/MyScript.js"></script>
Sign up to request clarification or add additional context in comments.

7 Comments

That is not going to work. If you omit the closing tag (or use a shorthand version with "/>" at the end), the browser won't load the script.
Even fixed, that's the exact line he said he's already using.
Thank you didn't even see that I used 'javascript' instead of 'text\javascript'
@user65439: Please mark as correct answer as it may help others
@MicrosoftDJ you're right! My bad. If you edit your answer I can remove the downvote.
|
0

You probably need to include jQuery into your View page:

<script type="text/javascript" src="~/Scripts/jquery.min.js"></script>

Make sure that's before any code that calls $().

(Note: You might have to change the exact filename to match what's in your project).

1 Comment

Its doubtful the script engine got to "undefined function" during a click .. before hitting "$ is not defined" with no jQuery included.

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.