10

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??

1
  • 5
    The error message is self-explanatory. Your break is not in a loop or switch. Return false to stop the .each loop. Commented May 6, 2013 at 10:43

5 Answers 5

23

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

$().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");
}

1 Comment

Nope, return won't stop the iteration. It should return false.
2

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)

Comments

1

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"
   });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.