0

I am using the code below, that iterating over select options. I checked if options value has already entered. It escapes from for-each but it doesn't exit from method.

yeniIlacBagla_ilacBagla: function(){
    $("#bagliIlaclar > option").each(function(){
        if(this.value===$("#baglanacakIlacID").val()){
            alert($("#baglanacakIlacAdi").val()+'\n adlı ilaç zaten bağlıdır!'); 
            return;
        }else{
            $("#bagliIlaclar").append($('<option></option>').val($("#baglanacakIlacID").val()).html($("#baglanacakIlacAdi").val()));
        }
    });
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
caglaror
  • 459
  • 1
  • 13
  • 28
  • 2
    You need to return false. http://stackoverflow.com/questions/2973333/how-to-dynamically-exit-a-jquery-each – Lucas Mar 22 '13 at 15:33

2 Answers2

5

According to the documentation of jquery I found the following

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.

Piero Divasto
  • 1,065
  • 13
  • 21
  • Technically, @caglaror is using `.each()` and not `jQuery.each`, though the answers for both happen to be the same. – Noyo Mar 22 '13 at 15:36
  • Thank you , but i can exit for-each with any `return` or `return false`, but it continue to iterate. How to check if its not carried on? – caglaror Mar 22 '13 at 15:39
1

From the documentation at http://api.jquery.com/each/ :

You can stop the loop from within the callback function by returning false.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Noyo
  • 4,874
  • 4
  • 39
  • 41