2

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

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Tim and @Raja! Hopefully this will become my first Nice Answer ;)
It sure is an Awesome Answer in my view just requires 3 more votes :-)
1

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() );
});

4 Comments

+1 for nice idea but what about (one example out of many) Ireland and Iraq? :) EDIT: even with 3 letters.. India and Indonesia
@shadow, yes i know it it does not hold much water in the official abbreviation of all countries.. I just posted it in case he was using a fixed list and the pattern fit every case..
Sure @Gaby I'm well aware of that - if this is indeed the case I do believe your way is better.
Tim: Yeah thanks for this, I was using the A2 ISO Country Codes in this case so it wouldn't have worked like that unfortunately. Thanks nonetheless :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.