ACP
ACP

Reputation: 35264

Is this break statement valid in jquery/javascript?

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

Upvotes: 10

Views: 25476

Answers (5)

Harish
Harish

Reputation: 1519

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

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

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)

Upvotes: 2

flavian
flavian

Reputation: 28511

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

Upvotes: 4

Ivan Drinchev
Ivan Drinchev

Reputation: 19591

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

Upvotes: 2

VisioN
VisioN

Reputation: 145478

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.

Upvotes: 23

Related Questions