0

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?

3 Answers 3

5

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.');
}
Sign up to request clarification or add additional context in comments.

2 Comments

The reason you keep return false is to short circuit.
@andlrc I know thanks. realised as soon as I edited in so scrapped that little comment. Appreciate the heads-up though!
1

You can use Array.prototype.every which will short circuit when a falsy value is returned:

var isTrue = [].every.call(required_fields, function(el) {
  return $(el).val();
});

if (isTrue) {
  console.log('Doing something');
}

I don't think you have an array but a jQuery object which is array like (got length and 0, 1, ... properties) So you can (ab)use the native Array prototype by setting the context with .call:

var every = Array.prototype.every;
every.call({ '0': 'a', '1': 'b', length: 2 }, console.log.bind(console));
// will output
// ['a', 0]
// ['b', 1]

Now that I think of it jQuery.fn.each will also short circuit if false is returned.

Comments

1

Two main options stand out: 1: Write a simple function that takes an array of jQuery objects and returns true if all items in the array have value

var allHaveValue = function(array){
    for(var i = 0; i < array.length; i++){
        if(!$(array[i]).val()){
            return false;
        }
    }
    return true;
};

// For your example
if(allHaveValue(required_fields)){
    // Proceed
} else{
    // Handle errors   
}

The other alternative is doing the same thing but using the underscore.js function for [every][1]

[1]: http://underscorejs.org/#every which does the same thing. The call would look like:

var allHaveValue = _.every(required_fields, function(item){
    return $(item).val();
});

if(allHaveValue)}{
    // Proceed
} else{
    // Handle errors
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.