Is this break statement valid in jquery/javascript?

22,125

Solution 1

The exception text is quite descriptive. You really can't use break statement inside if clause. In your case you should use return false to stop the .each() iteration.

Solution 2

A break statement is designed to end a for, while or do-while loop or a switch statement. It has no side effects where you are using it. What are you trying to achieve?

In your specific case, just return false

Solution 3

$().each is a function method, so you will terminate it with return

function setDropdownTextContains(dropdownId,selectedValue,hfId){
    $('#'+dropdownId+' option').each(function(){   
         if($(this).text() === selectedValue){
             $(this).attr("selected", "selected");
             return false; // <--
         }
    });
    $('#'+hfId).val("ModelName doesnt match");
}

Solution 4

to break you could just return false;, like

if($(this).text() === selectedValue){
    $(this).attr("selected", "selected");
    return false;
}

Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop)

Solution 5

As per jQuery documentation, break is to break out of the loop. You cannot use it inside if statement.

You can use return false instead.

jQuery.each(arr, function() {
      $("#" + this).text("Mine is " + this + ".");
       return (this != "three"); // will stop running after "three"
   });
Share:
22,125
ACP
Author by

ACP

Updated on August 01, 2022

Comments

  • ACP
    ACP almost 2 years

    I have a function which selects a text based on the input string. If both matches i make it selected. PFb the function,

    function setDropdownTextContains(dropdownId,selectedValue,hfId){
                $('#'+dropdownId+' option').each(function(){
    
                         if($(this).text() === selectedValue){
                             $(this).attr("selected", "selected");
                             break;
                         }
                });
                     $('#'+hfId).val("ModelName doesnt match");
            }
    

    I get the below error unlabeled break must be inside loop or switch ... What am i doing wrong??

  • VisioN
    VisioN about 11 years
    Nope, return won't stop the iteration. It should return false.