Adding html ID to rails select options

╄→尐↘猪︶ㄣ 提交于 2019-12-24 00:52:55

问题


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.


回答1:


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




回答2:


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 :)



来源:https://stackoverflow.com/questions/22799800/adding-html-id-to-rails-select-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!