Reputation: 9034
I have this simple code which is supposed to work but it isn't working. The if statement never seems to be true.
JS:
$(document).ready(function(e) {
var country = "United States";
$.each($('select[name="country"]').children('option'), function(){
if($(this).text() == country){
alert("found");
}else{
console.log("Not found");
}
});
});
HTML:
<select name="country" value="" >
<option value="0" >Afghanistan </option>
<option value="1" >Albania </option>
<option value="2" >Algeria </option>
<option value="3" >American Samoa </option>
.
.
.
.
I get no errors in the console.
Upvotes: 0
Views: 49
Reputation: 48415
The problem is that your option values have a trailing space " "
, so they do not match your country
(which has no trailing space).
"United States" != "United States "
Note: You could have easily debugged this by adding a breakpoint and checking both values.
Possible Solutions:
text()
result before you compare it (recommended)country
value (nonsense... but does work)Recommended Solution
if($(this).text().trim() == country){
alert("found");
}
You may want to check the browser compatibility for the trim()
function to ensure it matches your requirements. If it doesn't, then you may find this post of some interest.
Upvotes: 3
Reputation: 29
Use trim function in your if condition
if($.trim($(this).text()) == country)
Upvotes: 2