Mr Jones
Mr Jones

Reputation: 1198

Using jquery functions in MVC3- '$' is undefined

I apologize for my lack of jquery knowledge. I'm using jquery 1.6.2, and trying to attach a jquery function to an ActionLink. Here is my jquery function:

    <script type="text/javascript">
    $("addOperation").click(function () {
       $.ajax({
          url: this.href,
          cache: false,
          success: function (html) { $("#editor_rows").append(html); }
       });
       return false;
    });
    </script>

When I navigate to the page containing the script, the debugger comes back with the following:

    Microsoft JScript runtime error: '$' is undefined

This is pointing at the first occurence of '$'. To me, this sounds like it's not recognizing that this is a jquery call, but I haven't had trouble with this in the past. Not to mention, MVC3 should bundle and render all of the jscript files before the app loads. Any suggestions for me?

Upvotes: 2

Views: 703

Answers (1)

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35679

  1. Make sure your jquery script tag is above your script.

  2. Wrap your code in the document.ready event:

E.g. for 1

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script src="/path/to/your.script"></script>

E.g. for 2

$(document).ready(function() { 
     //Your code here
});

or shorter:

$(function() { 
       //Your code here
});

This will ensure all the JavaScript has loaded before your code is executed.

Upvotes: 3

Related Questions