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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Andre Lombaard
  • 6,985
  • 13
  • 55
  • 96
  • 1
    Are you sure the script path is correct ? – Raptor Jul 16 '13 at 06:04
  • your `MyScript.js` is not loaded. – Satpal Jul 16 '13 at 06:05
  • MVC 4? If yes , you have to add the Bundle in BundleConfig.cs (RegisterBundles method) – Cornel Urian Jul 16 '13 at 06: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). – volpav Jul 16 '13 at 06:09
  • Actually your jquery is not loaded yet just load jquer before you invoke the script – hackp0int Jul 16 '13 at 06:14
  • can you show the js callstack from your debug tool? from the information you supplied, it's hard to tell what's the problem, if like you said, your script is loaded and jquery is also loaded, there shouldn't be undefined error – Sean Jul 16 '13 at 06:22

2 Answers2

3

Try using :

<script type="text/javascript" src="~/Scripts/MyScripts/MyScript.js"></script>
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
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).

rossipedia
  • 56,800
  • 10
  • 90
  • 93
  • Its doubtful the script engine got to "undefined function" during a click .. before hitting "$ is not defined" with no jQuery included. – Simon Whitehead Jul 16 '13 at 06:16