将html ID添加到rails选择选项 [英] Adding html ID to rails select options

查看:75
本文介绍了将html ID添加到rails选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 simple_form 并尝试向每个特定 id > select_tag的选项。以下是我们的选择:

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" %>

添加<$ c后,这是可以的样子$ c> id / ids

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>

但这也可行(添加 id 到每个选项)

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>

我们想添加js行为以在特定的选项<时触发事件/ code>已被选中并计划使用 getElementById 来定位该选项。这就是我们想要在选项中添加 id 的原因。仅仅是篮球选项。

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.

推荐答案

尝试使用,

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

当我试用它时,它给了我html

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.

如果你也这样做,

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

这给了我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.

希望这有帮助

这篇关于将html ID添加到rails选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆