Is this break statement valid in jquery / javascript?

I have a function that selects text based on an input string. If both matches, I will make it selected. PFb 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 following error unlabeled break must be inside loop or switch ... What am I doing wrong?

+4
source share
5 answers

The text of the exceptions is quite descriptive. You really cannot use the break statement inside an if clause. In your case, you should use return false to stop the .each() iteration.

+17
source

$().each is a function method, so you end 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
source
Operator

A break intended to end a for, while or do-while or switch statement. It has no side effects when you use it. What are you trying to achieve?

In your particular case, just return false

+1
source

to break, you could just return false; , eg

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

Returning "false" from each function completely stops the loop through all elements (this is similar to using "break" with a normal loop). Returning “true” from the loop proceeds to the next iteration (this is similar to using “continue” with a normal loop)

+1
source

According to the documentation, jQuery break should exit the loop. You cannot use it inside an if statement.

Instead, you can use return false .

 jQuery.each(arr, function() { $("#" + this).text("Mine is " + this + "."); return (this != "three"); // will stop running after "three" }); 
0
source

Source: https://habr.com/ru/post/1479341/


All Articles