Tim
Tim

Reputation: 7056

array and loop in jquery

Hey all, I basically need to add a class to every <option> in a select. There is a different class to apply depending on the value of each option.

I need an easy way of doing something like

$('select option').each(function(){

       if($(this).val()=="Argentina"){  $(this).addClass("ar");  }
       if($(this).val()=="Brazil"){  $(this).addClass("br");  }
       if($(this).val()=="Czech"){  $(this).addClass("cz");  }

});

I have a very long list of countries, so using an array of some sort would be preferable, and then let the function filter in the if value = and the class name.

Many thanks

Tim

Upvotes: 3

Views: 302

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

Just an extra opinion in case the pattern (the class is just the first two chars in lowercase) from the example is a rule.

$('select option').each(function(){
  $(this).addClass( this.value.substr(0,2).toLowerCase() );
});

Upvotes: 2

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

Sure, use associative array:

var mapping = { "Argentina": "ar", "Brazil": "br", "Czech": "cz"};
$('select option').each(function(){
   var sClass = mapping[$(this).val()];
   if (sClass)
      $(this).addClass(sClass);
});

The if (sClass) is just failsafe to avoid crash when you forget to put country in the array. You can add some default class in such case.

Upvotes: 8

Related Questions