Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  78] [ 3]  / answers: 1 / hits: 27707  / 12 Years ago, mon, may 28, 2012, 12:00:00

I'm building 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 left empty, and if so 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 3rd action in contactform() I want to say that if validator() = true (i.e. there no inputs that are empty), then continue on to the next code.



I can't seem to return the value of validator(). Does anybody know the best way to do this?


More From » jquery

 Answers
12

Here is another solution using filter method:



function validator() {
return $(form input).filter(function() {
return $.trim(this.value).length == 0;
}).addClass(error).length == 0;
});

function contactform() {
...
if (validator()) {
// it's OK
} else {
// there are errors
}
}


UPDATE: Awesomely updated with the help of @am_not_i_am. Thanks!


[#85305] Saturday, May 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleew

Total Points: 70
Total Questions: 87
Total Answers: 117

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
;