Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add class to option in select

Based on the value of an option would that be possible to add a class to an option?

So if i have this:

   <select class="rubrique" name="ctl00">
    <option value="" selected="selected"></option>
    <option value="1">1</option>
    <option value="1">1</option>
    </select>

i'll get that:

<select class="rubrique" name="ctl00">
        <option class="" value="" selected="selected"></option>
        <option class="1" value="1">1</option>
        <option class="2" value="1">1</option>
        </select>
like image 517
user472285 Avatar asked Apr 22 '11 09:04

user472285


2 Answers

Yes, very easily, using the callback signature of addClass:

$('.rubrique option').addClass(function() {
    return this.value;
});
like image 147
lonesomeday Avatar answered Oct 07 '22 08:10

lonesomeday


$('.rubrique > option').each(function(){
    $(this).addClass($(this).val());
});

Edit: I am not sure if .val() is 100% correct here, you could also use this:

$('.rubrique > option').each(function(){
    $(this).addClass($(this).attr('value'));
});
like image 45
Damb Avatar answered Oct 07 '22 06:10

Damb