I create the very simple script below, in which I came with a question that I can't seem to find in the .each() documentation. As you see I would like to loop through a collection of jQuery objects and return either true or false (if one is false then the .each loop would break so the end result would be false)
For some reason the validation does not seem to work properly.
$('.with-validation').on('submit', function (e) {
if (isValid()) {
console.log('validation succeded');
return true;
} else {
console.log('validation failed');
return false;
}
});
function isValid () {
var $required = $('.required');
var $emails = $('.email');
var inputsValidation = function () {
return $(this).val().length > 0;
}
$required.each(inputsValidation);
return inputsValidation;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form class="with-validation">
<input name="lastname" class="required" type="text"></input>
<input name="firstname" type="text"></input>
<input name="phone" class="required" type="text"></input>
<input name="email" class="required email" type="text"></input>
<input name="confEmail" class="required email" type="text"></input>
<button class="submit-btn" type="submit">OK</button>
</form>
</body>
validateEmail()if it just returnstrue?.eachjust iterates over a jquery collection. It does not return any value. If you want to use.eachin your case you have to define external boolean flag and change it inside.each.