Follow-up to this question: Setting background-color of select options in JQuery
I have a page with multiple select boxes, as per the following:
<
I like @Arnar Yngvason's answer but I'll add this to the mix. This solution uses CSS classes so the styles can be easily changed without breaking the rest of the code.
.Red{background-color:#ff0000;}
.Blue{background-color:#0000ff;}
.Green{background-color:#00ff00;}
.Yellow{background-color:#ffff00;}
$("select").change(function(){
$(this).removeClass($(this).attr('class'))
.addClass($(":selected",this).attr('class'));
/*If you want to keep some classes just add them back here*/
//Optional: $(this).addClass("Classes that should always be on the select");
});
$("select").change(function() {
$(this).removeClass($(this).attr('class'))
.addClass($(":selected", this).attr('class'));
/*If you want to keep some classes just add them back here*/
//Optional: $(this).addClass("Classes that should always be on the select");
});
.Red {
background-color: #ff0000;
}
.Blue {
background-color: #0000ff;
}
.Green {
background-color: #00ff00;
}
.Yellow {
background-color: #ffff00;
}
JSFiddle
I've tested this on FireFox 31, IE 11 and Chrome 37