Return true / false for javascript function and then make stuff based on this

I am creating a contact form and I need help with the jQuery validator.

function contactform() { $("form #submit").on("click", function() { $("form input").removeClass("error"); validator(); // 3rd action goes here }); }); 

validator() checks to see if any input is empty, and if it adds an error class to it:

 function validator() { $("form input").each(function() { var value = $(this).val(); if (value.length <= 0) { $(this).addClass("error"); return false; } }); }); 

Now, for the third action in contactform() , I want to say that if validator() = true (i.e. there are no inputs that are empty), go to the next code.

I cannot return validator() value. Does anyone know a better way to do this?

+7
source share
3 answers

Here is another solution using the filter method:

 function validator() { return $("form input").filter(function() { return $.trim(this.value).length == 0; }).addClass("error").length == 0; }); function contactform() { ... if (validator()) { // it OK } else { // there are errors } } 

UPDATE : Awesomely updated using @am_not_i_am help . Thanks!

+7
source

The problem that you seem to encounter is that you have a nested function and a closure, which prevents the return of the value immediately.

Something like this should do the trick:

 function validator() { var result=true; $("form input").each(function() { var value = $(this).val(); if (value.length <= 0) { $(this).addClass("error"); result = false; } }); return result; }); 
+4
source
 function validator() { var result = true; $("form input").removeClass("error"); $('form input').each(function() { if(!$.trim(this.value)) { $(this).addClass('.error'); result = false; } }); return result; } function contactform() { $("form #submit").on("click", function() { if(validator()) { // pass the validation } else { // fail validation } // 3rd action goes here }); }); 
+3
source

All Articles