How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block
Related
How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block
When submit the form it runs both means to say code inside if is running and after else code is also running.
$("#new_chq").submit(function(){
var inputs = document.getElementsByName("val_2[]");
var i;
for (i = 1; i <= inputs.length; i++) {
$('#file_'+i).each(function() {
if(!$('#file_'+i).val() == ''){
$('#text_'+i).attr('required', '');
return false;
}
else{
return true ;
}
});
}
});
As you can see in docs:
We can break the $.each() loop at a particular iteration by making the
callback function return false. Returning non-false is the same as a
continue statement in a for loop; it will skip immediately to the next
iteration.
So, you need to move the form event handling after the jQuery each-loop.
Here is an example:
$("#new_chq").on('submit', function() {
var isValid = true;
$('[id^=file_]').each(function() {
if($(this).hasAttr('required') && !$(this).val()) {
isValid = false;
return false; // <- this breaks the loop
};
});
return isValid;
});
Please note, there are other errors in your code, such as $('#file_'+i).each loop, which has no sense - that is one element with unique id.
This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Closed 2 years ago.
I am trying to determine whether or not an array holds a certain item. If it does, I would like to hold the function, otherwise it should get added.
function addPacking(item){
data.packings.forEach(function(entry){
if(item.name == entry.name){
return;
}
});
data.packings.push(item);
}
Unfortunately, the data is pushed even when the if condition is met. How do I prevent this behaviour without using an else condition?
(I do not want to use else because my actual code is a lot more complex than this and I'd like to keep it readable)
Edit:
Does forEach execute asynchronously?
Old ways are sometimes the best. It's because you're passing a delegate function when calling .forEach. The return within the delegate is getting lost, and isn't applying to anything. To get your desired result, you'll want to exit the calling function addPacking. This can be done using a simply for loop.
function addPacking(item){
for (var i = 0; i < data.packings.length++; i++) {
if (item.name == data.packings[i].name) {
return;
}
}
data.packings.push(item);
});
This approach also supports older browsers, unlike some, every and forEach
You can't stop forEach execution other than throwing an exception (#Yoshi). Which should not be considered as an option to affect program code flow (#Me).
What you can do is to use another method some or every
function addPacking(item){
var contains = data.packings.every(function(entry){
return item.name != entry.name;
});
if(contains) {
data.packings.push(item);
}
}
Or
function addPacking(item){
var conatins = !data.packings.some(function(entry){
return item.name == entry.name;
});
if(contains) {
data.packings.push(item);
}
}
OLD question but in case someone else comes across this thread.
If you are using ECMAScript 6 you can use the Array find() method
var found = myArray.find(function (element) { return element === arrayToFind; });
so for this particular scenario would be:
function addPacking(item){
var foundItem = data.find(function(entry){ return entry.name == item.name});
if (foundItem) data.packings.push(foundItem);
}
see http://www.w3schools.com/jsref/jsref_find.asp for another worked example.
Return just aborts the function called in forEach, not your addPackings function.
function addPacking(item){
var isInPackings = false;
data.packings.forEach(function(entry){
if(item.name == entry.name){
isInPackings = true;
}
});
if (!isInPackings)
data.packings.push(item);
}
Yo are just returning from the child function but not from the parent function
function addPacking(item){
var check=false;
data.packings.forEach(function(entry){
if(item.name == entry.name){
check=true;
return;
}
});
if (check) return;
data.packings.push(item);
}
I want to break out of .each() iterations and it doesn't allow me to. Here is my code. Thanks for the help guys! Appreciate it.
$('#btn-submit-add').click(function(){
var answerField = 1;
$('.addAnswerChoice').each(function(){
var answerChoice = $(this).val();
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
$(this).focus();
return false; // this doesn't work
}
answerField++;
});
alert('doing stuff after');
});
My guess is that you're trying to return false from the click handler to cancel the submit. The way you have it your return false statement returns from the function you passed to .each(), which does break out of the .each() loop but it doesn't return from the outer function that is the click handler. So execution then continues with the statement after the .each(), i.e., the final alert. And your click is not cancelled. Try this instead:
$('#btn-submit-add').click(function(e){
var answerField = 1;
$('.addAnswerChoice').each(function(){
var answerChoice = $(this).val();
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
$(this).focus();
e.preventDefault();
return false;
}
answerField++;
});
});
jQuery passes the event object to your click handler (notice I've added a parameter called e), so you can use event.preventDefault() to stop the click from working.
This solution is almost like each only but short-circuits when the first true value is returned. So, you don't have to explicitly break out of the iterations.
Array.prototype.slice.call(document.getElementsByClassName("addAnswerChoice")).some(function(item) {
var answerChoice = item.value;
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
item.focus();
return true;
}
return false;
});
From documentation:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
Edit:
if #nnnnnn is right, the code should look like:
$('#btn-submit-add').click(function(){
var validated = true;
var answerField = 1;
$('.addAnswerChoice').each(function(){
var answerChoice = $(this).val();
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
$(this).focus();
validated = false;
return false;
}
answerField++;
});
if (!validated)
{
return false;
}
alert('doing stuff after');
});
I want to use return false to break a .each() but also return a value at the same time. How can I do this?
Please refer to a work-around function to see what I am trying to do:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store) {
if (state == store.state && store.category == "meyers") {
statehasstores = true;
return false; // break
}
});
return statehasstores;
}
What Id like to do in pseudo code is:
Function () {
for() {
if found {
return true;
}
}
return false;
}
You're doing it right...
Quote from http://api.jquery.com/each/
"We can stop the loop from within the callback function by returning false."
Be creative:
try {
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
throw store;
}
});
}
catch(e) {
// you got e with the value
}
No, I was just kidding, don't use this :). It came as an idea I liked to share.
Use a variable outside the loop to get the value and use it afterward.
var value;
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
statehasstores = true;
value = store; // added line
return false; //break
}
});
alert(value);
The way you're doing is just fine. I've tested on jsFiddle, see an example here.
It's not working for you? Can you show more context?
jQuery .each
Alternatively, you could use a for loop instead of each(), and just return the value.
What you're suggesting is the way to do it. I'd think of it less as a workaround and more as an idiom.
How about:
$.each( myObj, function( key, value ){
...
if( sthg... ){
myObj.somethingWentHorriblyWrong = true;
return false;
}
});
if( myObj.somethingWentHorriblyWrong ){
// ... do something, not forgetting to go:
delete myObj.somethingWentHorriblyWrong;
}
PS I was initially interested in what $.each(... actually returns. As it says on the relevant JQ page, "The method returns its first argument, the object that was iterated", but in fact the solution doesn't even require that you use that fact...
PPS Need a function that returns a value? Wrap in an outer function of course.
Okay I guess there's a little doubt about this point so maybe I'm making it clearer here :
When jquery doc says : "We can stop the loop from within the callback function by returning false." and you do :
Function () {
for() {
if found {
return true;
}
}
return false;
}
This doesn't mean that you're function will return true when find the searched element. Instead, it will always return false.
So to make your function work as you whish I propose to do so :
Function () {
variable found = false;
foreach() {
if found {
found = true;
return false; // This statement doesn't make your function return false but just cut the loop
}
}
return found;
}
Of course there are many other ways to perform this but I think this is the simplest one.
Coopa - Easy !
As others have noted from jQuery Each, returning false will only break from the loop not return the value, returning true however will 'continue' and immediately begin the next iteration. With that knowledge, you could somewhat simplify your code like this:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store){
// continue or break;
statehasstores = !(state == store.state && store.category == "meyers"))
return statehasstores;
});
return !statehasstores;
}
This of course is a little silly using the double negative, and has the side effect of saving 'true' to statehasstores for every false iteration and vice versa, however the end result should be the same and you no longer have that if statement.