2
$("#savebtn").click(function() {

    $('.mytable tr').each(function(){
      if($('.mytable tr').length < 1){
          alert("Nothing in the table!")
          return 
      }
    });
alert("You are still inside the click function")
});

Just having a bit of trouble with this one. I want to exit the jquery each loop AND click function altogether. But 'return' just takes me out of the each loop only. How do I completely exit the click function altogether?

Quaking-Mess
  • 505
  • 4
  • 12
  • 23
  • 1
    `$('.mytable tr').length < 1` inside .each loop with the same selector will never happen. BTW you can use return false inside the each loop to break out of it. What are you actually trying to do? – PSL Dec 12 '13 at 01:32
  • 1
    return still leaves me inside the function I want to break out of the function also within that if statement inside the each loop – Quaking-Mess Dec 12 '13 at 01:37
  • This is not a duplicate of the indicated question. Need to know how to break out of each() AND the function. – Andrew Jun 23 '17 at 19:03
  • Only thing I can think of is to mark a flag as true, break out of the each, and then check flag and return again. Seems messy. – Andrew Jun 23 '17 at 19:05

1 Answers1

3

If there is nothing in the table, the each function will actually never be executed (since the collection being iterated over is empty).

Perhaps you meant to put the condition as the first line in your click function:

$("#savebtn").click(function() {
    if($('.mytable tr').length < 1) {
        alert("Nothing in the table!");
        return;
    }

    $('.mytable tr').each(function() {
        doSomething(this);
    });

    alert("You are still inside the click function")
});

As a side note, if the each function is the only thing in this block, you do not need to do anything special for the empty-table case, since the each function will simply be executed zero times.

lc.
  • 113,939
  • 20
  • 158
  • 187
  • this is good thanks, better to put the if statement first at the top of the function rather than inside each loop. – Quaking-Mess Dec 12 '13 at 01:45
  • this doesnt answer the original question of breaking from each and function. Oh well, maybe the duplicate Q & A will. - nope it doesnt. – Andrew Jun 23 '17 at 19:02