How can I create a colors dropdown menu in ruby on rails 3?
I know how to do it in html, css and javascript as following but i dont know how in ruby on rails 3.
Ideally using collection_select or collection_options_for_select other collection objects that build <select>
's and <options>
's. Using these would be preferred to manually looping through the collection and spitting out pieces and styling each piece though that could be done.
Code partial of what I am trying to get is:
<select>
<option value="">Highlight</option>
<option value="#000000" style="background-color: Black;color: #FFFFFF;">Black</option>
<option value="#808080" style="background-color: Gray;">Gray</option>
<option value="#A9A9A9" style="background-color: DarkGray;">DarkGray</option>
Full Code is at:
http://pietschsoft.com/post/2004/09/20/Color-the-background-of-items-in-a-Dropdown-box-in-your-HTML-pages.aspx
Rails Helper options_for_select
absolutely allows you to provide styling information for individual options.
This is straight from the documentation of options_for_select
options_for_select([ "Denmark", ["USA", {:class=>'bold'}], "Sweden" ], ["USA", "Sweden"])
gives
<option value="Denmark">Denmark</option>\n<option value="USA" class="bold" selected="selected">USA</option>\n<option value="Sweden" selected="selected">Sweden</option>
and
options_for_select([["Dollar", "$", {:class=>"bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]])
gives
<option value="$" class="bold">Dollar</option>\n<option value="DKK" onclick="alert('HI');">Kroner</option>
And in your case it would be
options_for_select([["Black", {:style => "background-color: Black; color: #ffffff"}],
["Gray", {:style => "background-color: Gray"}],
["DarkGray", {:style => "backgorund-color: DarkGray"}]])
The built in helpers don't support it as far as I know.
However you can roll your own with:
def options_colors(colors)
colors.collect do |color, code|
"<option value='#{code}' style='background-color:#{code};'>#{color}</option> "
end.join
end
and then use it as follow:
@colors = ["Red" => "#f00", "Blue" => "blue"]
select_tag("setting[bg_color]", options_colors(@colors))