Reputation: 2485
I am checking when I user submits a form to check all inputs are filled, but my code carries on even if I return to escape the function.
function save(e) {
$('#storename, #offer').each(function() {
if ($(this).val() == '') {
alert("Please fill in all the required fields.");
return false;
}
});
//Don't Run Below if inputs are empty..
}
Upvotes: 1
Views: 72
Reputation: 1647
I'm late, but super elegant).
function save(e) {
return !$.grep($('#storename, #offer'), function(el){
return !$(el).val()}
).length;
}
Upvotes: 0
Reputation: 2484
function save(e) {
var empty = false;
$('#storename, #offer').each(function() {
if ($(this).val() == '') {
alert("Please fill in all the required fields.");
empty = true;
}
});
if(empty) return false;
//Dont Run Bellow if inputs are empty..
}
You don't actually return any value from save(e)
function. The only function returning now is the anonymous function inside each()
. You need to handle information about empty fields outside the anonymous function like above.
Upvotes: 1
Reputation: 388316
You can use a flag to check the validity
function save(e) {
var valid = true;
$('#storename, #offer').each(function () {
if ($(this).val() == '') {
alert("Please fill in all the required fields.");
valid = false;
return false;
}
});
if (!valid) {
return false;
}
//Dont Run Bellow if inputs are empty..
}
when you return from the each
loop, you are only returning from the each callback
method, not from the save
method. You can use a flag to check whether the fields are valid as shown above and use it to return from save
if needed
Upvotes: 4