如何在select_tag rails上的options_for_select中添加id

时间:2016-06-09 03:39:29

标签: ruby-on-rails select

我试图在rails上实现select_tag。我希望在id上添加每个选项值的select选项。这是我的select_tag代码:

<%= select_tag "type", options_for_select(@form_type, :selected => form.values.first.form_type._id, id: "#{form.values.first.form_type.key}"), name: "core_template[form][#{index.to_s}][type]", class: "form-control change-type", id:"core_template_type#{index.to_s}", :prompt => "Select Type", :required=>"required" %>

并且select_tag生成如下的html:

<select name="core_template[form][0][type]" id="core_template_type0" class="form-control change-type" required="required"><option value="">Select Type</option><option selected="selected" value="57562dbba3399025ca000001">Check Box</option>
<option value="57562ddaa3399025ca000003">Free Text</option>
<option value="57562dcda3399025ca000002">Radio Button</option>
<option value="57578fc6a339900db7000002">Text Area</option></select>

我想为每个选项值添加id,如下所示:

<select name="core_template[form][0][type]" id="core_template_type0" class="form-control change-type" required="required"><option value="">Select Type</option><option selected="selected" value="57562dbba3399025ca000001">Check Box</option>
<option value="57562ddaa3399025ca000003" id="free_text">Free Text</option>
<option value="57562dcda3399025ca000002" id="radio_button">Radio Button</option>
<option value="57578fc6a339900db7000002" id="text_area">Text Area</option></select>

怎么做? 谢谢大师

1 个答案:

答案 0 :(得分:0)

您可以通过这种方式添加自定义类或ID。直接从文档here复制。我已经在Rails v6.0.0.beta3应用程序中对其进行了测试和测试,并且可以正常工作。

您可以选择提供HTML属性作为数组的最后一个元素。

options_for_select([ "Denmark", ["USA", {class: 'bold'}], "Sweden" ], ["USA", "Sweden"])
# => <option value="Denmark">Denmark</option>
# => <option value="USA" class="bold" selected="selected">USA</option>
# => <option value="Sweden" selected="selected">Sweden</option>

options_for_select([["Dollar", "$", {class: "bold"}], ["Kroner", "DKK", {onclick: "alert('HI');"}]])
# => <option value="$" class="bold">Dollar</option>
# => <option value="DKK" onclick="alert('HI');">Kroner</option>

您还可以通过选中此answer来添加自定义数据属性。

注意:如果使用浏览器控制台进行检查,它可能不会出现在ul > li标记中,特别是如果您将options_for_select与Select2一起使用,至少对我而言不是这样。只是知道那里可能不会出现。通过尝试此操作,我可以确认它是否可用-$('.bold').val()