MRAN MRAN - 2 months ago 6
jQuery Question

TypeError: $ is not a function at jQuery function

I have a simple jQuery script in a WordPress plugin that is using a jQuery wrapper:

$("#myForm").submit(function(e){

e.preventDefault();

if ($('input[name="username"]').val() == "" || $('input[name="password"]').val() == "")

$("#NotesArea").html("Please enter both Username and Passnumber");

else

$.post($(this).attr("action"), $(this).serialize())

.done(function(data) { $("#NotesArea").html(data); })

.fail(function(jqXHR, textStatus) {alert( "Request failed: " + textStatus );});

});


I am calling this script from within the WordPress Dashboard and i am getting always this error:


Uncaught TypeError: $ is not a function


Alright, I made it like this, no errors but the code doesn't work!

(function($){
$("#myForm").submit(function(e){

e.preventDefault();

if ($('input[name="username"]').val() == "" || $('input[name="password"]').val() == "")

$("#NotesArea").html("Please enter both Username and Passnumber");

else

$.post($(this).attr("action"), $(this).serialize())

.done(function(data) { $("#NotesArea").html(data); })

.fail(function(jqXHR, textStatus) {alert( "Request failed: " + textStatus );});

});
})(jQuery);

Answer

Wordpress use noConflict which removes the $ alias

Wrap your code in the following IIFE and you can continue using $ inside it

(function($){
  /* your code*/

})(jQuery);