I am making a form validation function and have the following code for it
(function ( $ ) {
$.fn.validate_thing = function (success_call_back) {
var call_back = true;
debugger;
if (!this.is('form')) {
return false;
}
$('input.empty').each(function() {
if(!$(this).text()) {
alert($(this).attr('name'));
call_back = false;
}
});
}
})(jQuery);
The problem is that when the page loads I get a javascript error saying that ‘object is not a function’ on the (jQuery) line. If I step through this with the debugger I don’t get this problem. If I put this in a document ready function I don’t get this problem. I’m thinking that it might have something to do with jQuery not being loaded with this script is run, but I include the jQuery library before the library that contains this code, not to mention if I don’t do this in a closure, i.e. do this
$.fn.validate_thing = function (success_call_back) {
var call_back = true;
debugger;
if (!this.is('form')) {
return false;
}
$('input.empty').each(function() {
if(!$(this).text()) {
alert($(this).attr('name'));
call_back = false;
}
});
}
it works.
So I have a few work arounds for this problem but I’d still like to know why this is happening. Thanks in advance.
here’s what i have before it in the javascript page
engine = new function() {
this.request = function ( params ) {
var data = params.data ? params.data : '';
if (params.url) {
var url = params.url;
var page = document.URL.split('/').pop();
var page = page.split('.')[0];
data += 'content_page='+page+'.tpl';
}
else {
var url = document.URL;
}
debugger;
if (params.action) {
data += data ? '&action='+params.action : "action="+params.action;
}
$.ajax({
url : url,
type : 'POST',
data : data,
dataType: 'json',
success : function(data) {
debugger;
if (data && data.partials) {
for (var key in data.partials) {
var element = data.partials[key];
$('#'+element.partial_name).replaceWith(element.partial_content);
}
}
},
error : function (jqXHR, textStatus, errorThrown) {
debugger;
alert('ajax error: '+errorThrown);
}
}).success(params.success);
}
}
If you get an error in the last line, it is likely that JavaScript interprets the parenthesis
( function() { ... } )as function call of whatever precedes the code. This can happen if you forgot a semicolon in the previous line.Consider this:
Note that the semicolon is missing after
fooand therefore JavaScript interprets the code asfoo(...), which throws the error