Ruby-on-rails rails select_tag 选定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7347039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails select_tag selected value
提问by lamrin
For the code given below I wanted to keep the select box selected with the value that is passed.
对于下面给出的代码,我想使用传递的值保持选择框的选中状态。
But this doesn't work:
但这不起作用:
@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,:selected=>2011) %>
Please advise me how to go about it.
请告诉我如何去做。
Thanks
谢谢
回答by M Tariq Aziz
Remove the :selected=>part.
取下:selected=>零件。
Syntax:
句法:
options_for_select(@options, @selected_options)
Usage:
用法:
options_for_select(1..5, 3) # creates a range 1..5 , with 3 as selected by default
回答by manish nautiyal
<%= select_tag "page_type", options_for_select(@page_type.collect{ |u| [u.data_name, u.id]}, :selected=>@page.page_type), {:class =>"select_combobox",:onchange=>"reset_form(this.id,'page_type_msg');"} %>
this works for me :)
这对我有用:)
回答by harrya
Just to clarify @M Tariq Aziz answer:
只是为了澄清@M Tariq Aziz 的回答:
Your code should look like this:
您的代码应如下所示:
@yrs =[2011,2010,2009,2008]
<%= select_tag 'year', options_for_select([["Select" , "" ]] + @yrs.to_a,2011) %>
The general format for select tag is:
select标签的一般格式是:
<%= select_tag 'year', options_for_select(:collection, :selected) %>
回答by Snips
I was using a select box as part of a Search bar, so wanted to have the default first option selected on first presentation of the form, but then retain the chosen option thereafter. This works great:
我使用选择框作为搜索栏的一部分,因此希望在表单的第一次演示中选择默认的第一个选项,但此后保留选择的选项。这很好用:
<% styles = Styles.all.sort %>
<%= form_tag styles_path, :method => 'get' do %>
<p>
Search: style
<%= select_tag :search_style, options_for_select(styles, selected: params[:search_style]) %>
with colour
<%= text_field_tag :search_color, params[:search_color] %>
<%= submit_tag "Search" %>
</p>
<% end %>

