Reputation: 355
I have a nested loop written in jquery and return false inside my child loop keeps appending the same text to the parent row. My code,
$('#listingProducts ul.msRows li.msFullfillment').each(function(index) {
if(typeof $('#hfOrd'+index).val() != 'undefined'){
var $this = $(this);
var orderId = $('#hfOrd'+index).val();
// repainting logic
$('body').append(data);
$('#ajaxProducts ul.displayPoints li').each(function(index){
var $child = $(this);
if(typeof $('#hfAjaxOrderId'+index).val() != 'undefined'){
var ajaxOrderId = $('#hfAjaxOrderId'+index).val();
//alert(orderId+' '+ ' '+ajaxOrderId);
if(ajaxOrderId === orderId){
// replace the div here..
var anchorText = $child.find("#pointsLineAjax .redeem").text();
$this.find("#pointsLine .redeem").text(anchorText);
return false;
}
}
});
}
});
Return false inside child loop doesnt go back to the parent. That doesnt seem to write it to the corresponding row. What am i missing here..
Upvotes: 0
Views: 539
Reputation: 16990
Returning false
only breaks out of the inner loop in a jQuery loop, there is a good explanation for the reason in this answer.
The problem here is that while you can return false from within the .each callback, the .each function itself returns the jQuery object. So you have to return a false at both levels to stop the iteration of the loop. Also since there is not way to know if the inner .each found a match or not, we will have to use a shared variable using a closure that gets updated.
Try the following:
$('#listingProducts ul.msRows li.msFullfillment').each(function(index) {
var continueLoop = true;
if($('#hfOrd'+index).length){
var $this = $(this);
var orderId = $('#hfOrd'+index).val();
// repainting logic
$('body').append(data);
$('#ajaxProducts ul.displayPoints li').each(function(index){
var $child = $(this);
if($('#hfAjaxOrderId'+index).length){
var ajaxOrderId = $('#hfAjaxOrderId'+index).val();
//alert(orderId+' '+ ' '+ajaxOrderId);
if(ajaxOrderId === orderId){
// replace the div here..
var anchorText = $child.find("#pointsLineAjax .redeem").text();
$this.find("#pointsLine .redeem").text(anchorText);
continueLoop = false;
return false;
}
}
});
};
return continueLoop;
});
Upvotes: 2