Jake Petroules
Jake Petroules

Reputation: 24140

Return from inner function in JavaScript?

I have a jQuery-powered JavaScript function which iterates over a list of fields and checks to see whether they are empty; if so, blocks the submission of the form.

required_fields.forEach(function(field) {
    if (field.val() == '')
    {
        field.addClass('field-highlight');
        return false;
    }
    else
    {
        field.removeClass('field-highlight');
    }
});

// I want to return to here from the return false point

How can I structure this differently to do what I want?

Upvotes: 2

Views: 368

Answers (5)

user113716
user113716

Reputation: 322452

If your required_fields is a jQuery object, you could just do this:

var stop = required_fields.removeClass('field-highlight')
                          .filter("[value == '']").addClass('field-highlight')
                          .length;

return !!stop

Or perhaps more efficient like this?

var stop = required_fields.filter('.field-highlight').removeClass('field-highlight')
                          .end().filter("[value == '']").addClass('field-highlight')
                          .length;

return !!stop

Upvotes: 0

JeremyWeir
JeremyWeir

Reputation: 24368

Did you write the "forEach" function? If so, that could check the return value of the anon function, and if it is ever false, stop iterating.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754565

It sounds like you want to do the following

  • Update the elements with the field-highlight class based on whether or not they have a value
  • Block the form submission if any are empty

If so then try the following

var anyEmpty = false;
required_fields.forEach(function() {
  if ($(this).value() == '') {
    $(this).addClass('field-highlight');
    anyEmpty = true;
  } else {
    $(this).removeClass('field-highlight');
  }
});

if (anyEmpty) {
  // Block the form
}

Upvotes: 0

Salman Paracha
Salman Paracha

Reputation: 1703

use a boolean in the forEach closure, which would be set to true, if the field value is empty. Check that value before submission of form

Upvotes: 0

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

Just use a variable to keep track of the validation:

var is_valid = true;

required_fields.forEach(function(field) {
    if (field.val() == '') {
        field.addClass('field-highlight');
        is_valid = false;
        return false;
    } else  {
        field.removeClass('field-highlight');
    }
});

return is_valid;

Or, you can just use the field-highlight class as well:

required_fields.forEach(function(field) {
    if (field.val() == '') {
        field.addClass('field-highlight');
        return false;
    } else  {
        field.removeClass('field-highlight');
    }
});

return $('.field-highlight').length == 0;

Upvotes: 5

Related Questions