user3284463 user3284463 - 1 year ago 62
Javascript Question

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.


$(document).ready(function(e) {
var country = "United States";

$.each($('select[name="country"]').children('option'), function(){
if($(this).text() == country){
console.log("Not found");




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


Answer Source

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){

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download