我想使用FormHelper
重现以下选择结构<select data-placeholder="Choose a Country..." name="select2" class="required select">
<option value=""></option>
<option value="opt2">India</option>
<option value="opt2">United States of America</option>
</select>
<%= f.collection_select(:country_id, @countries, :id, :name, { :prompt => true },
{ :class => 'select', :selected => params[:country_id], :date => {:placeholder => 'Choose a Country...' }}) %>
但是Placeholder标记没有被选中,它显示Please Select
答案 0 :(得分:1)
此:
= collection_select("user", "country_id", @countries, :id, :name, {:prompt => true}, { :class => 'select', :selected => 1, "data-placeholder" => 'Choose a Country...' })
返回此html(我添加user
进行测试):
<select class="select" data-placeholder="Choose a Country..." id="user_country_id" name="user[country_id]" selected="selected"><option value="">Please select</option>
<option value="1">Russia</option>
<option value="2">USA</option></select>
所以这就是你所期望的,但对我而言,它并没有显示占位符。要显示它,只需将prompt
更改为占位符标题:
f.collection_select(:country_id, @countries, :id, :name, {:prompt => 'Choose a Country...'}, { :class => 'select', :selected => params[:country_id])
这对我来说很好。
答案 1 :(得分:1)
来自rails文档
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
根据语法:selected
参数应该进入options
而不是html_options
您需要做的就是从:selected
中移除html_options
参数并将其包含在options
<%= f.collection_select(:country_id, @countries, :id, :name, { :prompt => true, :selected => params[:country_id] }, { :class => 'select', :date => {:placeholder => 'Choose a Country...' }}) %>