Change the option color chosen in select

1

I have a select called "priority" that has 3 options: high, medium and low.

I would like that when you select high, I put the name "high" in red, "medium" in yellow and "low" in green. So in my view, I will get my list of priorities with the names: high, medium, low in these 3 colors to quickly see which priorities are more important than others.

Code of select :

<% form.select :prioridad, ["alta", "media", "baja"], id: : tarea_prioridad %> 

What I intend to do, but I do not succeed, is the following:

<% form.select :prioridad, ["alta", {syle=>color:"red"},"media",{syle=>color:"green"}, "baja",{syle=>color:"yellow"}], id: : tarea_prioridad %>
    
asked by mantisa 14.06.2018 в 14:14
source

1 answer

0

I see a few details:

  • You are using syle instead of style , which is the correct name of the attribute.
  • However, instead of using style , you should delegate your styles to class , which is the correct way to separate style structure (html) (css).
  • You start your line with <% instead of <%= that is used when returning a value to the template.
  • id: : tarea_prioridad is unnecessary, because if your object is tarea and the attribute is prioridad , it will automatically generate id="tarea_prioridad" when you render the template.
  • You should use options_for_select instead of an array as a parameter of select , since that method allows you to customize the <option> elements that your <select> will contain.

The line to use should be something like:

 <%= form.select :prioridad, options_for_select([["alta", {class: 'high'}],["media",{class: 'middle'}], ["baja",{class: 'low'}]]) %>

Then you must add the styles in your css, which would end up giving you an html like the one described below:

.low {
  color: green;
}

.middle {
  color: yellow;
}

.high {
  color: red;
}
<select name="tarea[prioridad]" id="tarea_prioridad">
  <option class="high" value="alta">alta</option>
  <option class="middle" value="media">media</option>
  <option class="low" value="baja">baja</option>
</select>

Take into account that the <option> are rendered differently for each OS , so the options for style is limited.
If you need more control over the style of <option> , you should already use JS libraries like select2 or chosen .

    
answered by 15.06.2018 / 18:34
source