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?
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?
3 Answers
Reset to default 8Here 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!
The problem you seem to encounter is that you have a nested function and closure, which prevents you from returning the value directly.
Something like that 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;
});
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
});
});