下拉菜单中的电话国家代码的国家选择
问题描述:
Rails noob here在这里提出一个问题。下拉菜单中的电话国家代码的国家选择
我试图让用户输入他们的电话号码。表格中包含国家代码,地区代码和电话号码的单独字段。
<% form_tag phones_path, :method => 'get' do %>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>
我想将COUNTRYCODE字段转换为国名的下拉选择,并自动显示在选择实际的国家代码。例如用户选择美国,显示+1。我将存储国家名称和数字代码。
我想我需要使用collection_select的下拉和javascript组合来刷新显示。但我有点失落如何继续。请问任何善良的灵魂都会提供一些提示吗?
答
首先应该建立在你的控制器的哈希看起来像:
@countries = { "United States" => "+1", "Switzerland" => "+41" }
然后创建为国家选择列表,并添加一个onchange JavaScript事件处理程序的选择列表:
<% form_tag phones_path, :method => 'get' do %>
<th>
<%= select_tag :country,
options_for_select(@countries),
:onchange => "document.getElementById('countrycode').value = this.options[selectedIndex].value;"
%>
</th>
<th><%= text_field_tag :countrycode %></th>
<th><%= text_field_tag :areacode %></th>
<th><%= text_field_tag :search, params[:search] %></th>
<th><%= submit_tag "Search", :name => nil %></th>
<% end %>
注:我已经使用标准的JavaScript onchange事件,如果你使用jQuery或prototypeJS这可能会写得更短,更清洁:)
答
你也可以这样做:
<%= f.collection_select(:subject_heading_source_id, SubjectHeadingSource.all, :id, :name, :prompt => "Please select...") %>
这取决于地方有选择的在表中描述的内容,并使用“的form_for”的方法来建立你的形式,所以它可能不完全适用。
编辑:意外提交,对不起。
我使用jQuery找到元素和更新:
$("#phones_path_country_code").attr("selected", value_of_selection)
你把这个部分分为:平变化=>“...”,在再培训局位HTML选项。
我的jQuery很可能关闭,但你可以在api站点获得更好的主意。 jQuery
备注:如果您的国家/地区的代码有模型,则可以使用[options_from_collection_for_select](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i- options_from_collection_for_select)而不是散列;) – sled 2011-05-17 14:55:44
好评。我个人会尽量避免手动建立选择选项 – jaydel 2011-05-17 15:50:03
这对我来说是一个很好的开始,并且运作良好。我想将countrycode text_field_tag设置为不可编辑的显示而不是表单。如果我使用:禁用,它不会被发送。我应该采取其他方式吗? – Julien 2011-05-17 16:01:44