Reputation: 197
for a personal project, I want to change the color of my select tag, dynamically, according the option selected.
I've succeed to achieve this result with both browsers.(I'm targeting only chrome and firefox for this).
However, I've noticed something odd with firefox. Let me explain, with some code.
While I can get the color value of the selected option & then apply this one to the select tag with this piece of code under chrome :
$('select.label').change(
function(){
var sl_col_label = $(this).find('option:selected').css('background-color');
$(this).css('background',sl_col_label);
}
).change();
}
This doesn't work with Firefox, I basically try to get back the value of the color of the selected option based on its inline color style.
To make it working under firefox as well, I have to get the color value through an attribute such as value as an example.
$('select.label').change(
function(){
var sl_col_label = $(this).find('option:selected').attr('value');
$(this).css('background',sl_col_label);
}
).change();
}
Here is the HTML:
<select name="label" id="" class="label">
<option style="background-color:blue;" value="blue">blue</option>
<option style="background-color:red;" value="red">red</option>
<option style="background-color:green;" selected value="green">green</option>
<option style="background-color:yellow;"value="yellow">yellow</option>
</select>
To play with it directly: check this fiddle
Upvotes: 2
Views: 9711
Reputation: 8033
The problem is: you put change
inside another function. You should put it inside $(document).ready()
function. THis can be your js code:
$(document).ready(function(){
setColor();
$('select.label').change(function(){
setColor();
});
});
function setColor()
{
var color = $('select.label').find('option:selected').attr('value');
$('select.label').css('background', color);
}
Here is the working fiddle.
Upvotes: 3