ruby on rails: how to change BG color of options in select list
I want to pull list of colors from model and put the color select list in the view. Options have value as color code. I want to change the background color of options same as its value. Below are two ways I tried to do but it comes out that it changes color for whole select list but not for individual options with individual colors.
<p>
<b>Background color</b><br />
collection_select(:setting, :bg_color, @colors, :code, :name,
options ={:prompt => "-Select a color"}, html_options = {:style => "background-color: #3f3"})
</p>
<p>
<b>New Background color</b><br />
select_tag("setting[bg_color]", "<option>-Select a color</option>" +
options_from_collection_for_select(@colors, :code, :name, html_options = {:style开发者_如何学编程 => "background-color: #3f3"}))
</p>
I want it to generate something similar to:
<option value='color_code' style='background-color: color_code' >color_name</option>
this way, the colors in options are also visible to the users.
anyway we can customize the options?
thanks in advance.
The rails helpers don't support html_options like that. You can make your own helper method, though.
def options_with_colors(colors)
colors.collect do |color, code|
"<option value='#{code}' style='background-color:#{code};'>#{color}</option> "
end.join
end
Call like:
@colors = ["Red" => "#f00", "Blue" => "blue"]
select_tag("setting[bg_color]", options_with_colors(@colors))
精彩评论