Reputation: 35264
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
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
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
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
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