John Stephens John Stephens - 6 months ago 10
Javascript Question

JavaScript: Execute function only if all items in array are true?

I have this code:

// Required fields is an array of objects

required_fields.each(function() {

// Check each field: If it has no value, do nothing.
if( !$(this).val() ) {
return false;
}

// If all the fields are there, do something.
else {
alert('Doing something.');
}

});


I'm sure you can see the problem. Having the
alert
in the
.each()
function causes the alert to trigger for every item in the array. But what I want is to only trigger the event if ALL of the array items have a value—that is, if none
return false
.

What is the correct way to trigger something only if all the array items pass?

Answer

Just implement a little counter for each value.

var valueCount = 0;

required_fields.each(function () {
  if (!$(this).val()) {
    return false;
  } else {
    valueCount++; // increment to say has value
  }

});

if (valueCount == required_feilds.length) {
  alert('Doing something.');
}