Domanda

We're using simple_form and trying to add an id to each of a specific select_tag's options. Here is our select:

<%= f.input :category, collection: %w{ Football Basketball Golf Soccer }, :include_blank => "Choose one" %>

Here is what it can look like after we add the id/ids

<select class="select required form-control" id="sport_category" name="sport[category]">
  <option value="">Choose one</option>
  <option value="Football">Football</option>
  <option id="addBehavior" value="Basketball">Basketball</option>
  <option value="Golf">Golf</option>
  <option value="Soccer">Soccer</option>
</select>

But this would work as well (adding an id to each option)

<select class="select required form-control" id="sport_category" name="sport[category]">
  <option value="">Choose one</option>
  <option id="football" value="Football">Football</option>
  <option id="basketball" value="Basketball">Basketball</option>
  <option id="golf" value="Golf">Golf</option>
  <option id="soccer" value="Soccer">Soccer</option>
</select>

We want to add js behavior to trigger an event when a specific option is selected and were planning to use getElementById to target the option. This is why we want to add an id to the options..really only the Basketball option.

È stato utile?

Soluzione

Try using,

<%= f.input :category, collection: %w{ Football Basketball Golf Soccer }.map { |category| [category, category, {:id => category}]}, :include_blank => "Choose one" %>

When I tried it, it gave me the html

<option value="">Choose one</option>
<option id="football" value="Football">Football</option>
<option id="basketball" value="Basketball">Basketball</option>
<option id="golf" value="Golf">Golf</option>
<option id="soccer" value="Soccer">Soccer</option>

There might be a cleaner way to do it, but it works.

If you also do,

<%= f.input :category, collection: [["Football", "football"], ["Basketball", "basketball", {:id => "basketball"}], ["Golf", "golf"], ["Soccer", "soccer"]], :include_blank => "Choose one" %>

That gave me the html,

<option value="">Choose one</option>
<option value="Football">Football</option>
<option id="basketball" value="Basketball">Basketball</option>
<option value="Golf">Golf</option>
<option value="Soccer">Soccer</option>

Again, there might be a cleaner way to do it! But it works for me at least.

Hope this helps

Altri suggerimenti

You can use:

<%@array = ['Football', 'Basketball', 'Golf Soccer']%>

<%= f.select :category, ,options_for_select([['Choose One']] + @a.collect{|p| [p,{:id => p]}) %>

Hope it helps :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top