0

I have the following form

<input class="required" id="name" value="some content"/>
<input class="required" id="address" value=""/>
<input class="required" id="lastname" value="some content"/>

and the following jQuery function. It contains a .each() loop to check some inputs. When the check fails, the function should break and return false.

function check() {
  $('.required').each(function() {
    var input = $(this);
    console.log(input.attr('id'));

    if (input.val() == null || input.val() == '') {
      console.log('*** Failed ***');
      return false;
    }
  });

  console.log('Other code');
  return true;
}

Unfortunately, when I run the code I see the following output:

name
address
*** Failed ***
Other code

The .each() loop correctly stops after the first failure, but the check function seems to keep running. How can I break its execution? Here's a jsFiddle.

1
  • You return false from each anonymous function, not from check() Commented Apr 12, 2016 at 9:00

3 Answers 3

2
function check() {
  var valid = true;
  $('.required').each(function() {
    var input = $(this);
    console.log(input.attr('id'));

    if (input.val() == null || input.val() == '') {
      console.log('*** Failed ***');
      valid = false;
      return false;
    }
  });

  if (!valid) return false;

  console.log('Other code');
  return true;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I give you credit but you should at least explain why it would work (even it is quite comprehensive code)
0

The return false only breaks the $.each statement, but the function go on with the next instruction (console.log('Other code');).

Comments

0

I've found an alternative solution. The idea is to get the .required inputs and then make a classic for loop. This avoids the each() loop and the anonymous function.

function check() {
  var required = $('.required');
  var size = required.size();

  for (var i = 0; i < size; i++) {
    var input = $(required[i]);
    console.log(input.attr('id'));

    if (input.val() == null || input.val() == '') {
      console.log('*** Failed ***');
      return false;
    }
  }

  console.log('Other code');
  return true;
}

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.