Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding html ID to rails select options

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.

like image 968
tMTboss Avatar asked Jan 26 '26 14:01

tMTboss


2 Answers

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

like image 166
strivedi183 Avatar answered Jan 29 '26 03:01

strivedi183


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

like image 23
Rajesh Omanakuttan Avatar answered Jan 29 '26 04:01

Rajesh Omanakuttan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!