简体   繁体   中英

Break jQuery function execution on failure inside .each() loop

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 .

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;
}

return false仅会破坏$.each语句,但是该函数会继续执行下一条指令( console.log('Other code'); )。

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM