Ikhlak S.
Ikhlak S.

Reputation: 9034

Simple if statment not working

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.

JsFiddle

Upvotes: 0

Views: 49

Answers (2)

musefan
musefan

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:

  1. Trim the text() result before you compare it (recommended)
  2. Remove the spaces from within the HTML (I would do this too anyway)
  3. Add an extra space to the 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

Ranvir S.
Ranvir S.

Reputation: 29

Use trim function in your if condition

if($.trim($(this).text()) == country)

Upvotes: 2

Related Questions