【问题标题】:drop down country selection for phone country code in railsRails中电话国家代码的下拉国家选择
【发布时间】:2011-12-13 03:39:55
【问题描述】:

Rails 菜鸟在这里提出问题。

我正在尝试让用户输入他们的电话号码。表单目前包含国家代码、区号和电话号码的单独字段。

<% 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 字段转换为国家名称的下拉选择,并在选择时自动显示实际的国家代码。例如,用户选择 USA,并显示 +1。我将存储国家名称和数字代码。

我想我需要结合使用collection_select 下拉菜单和javascript 来刷新显示。但我对如何进行有点迷茫。请好心人给点提示好吗?

【问题讨论】:

    标签: javascript ruby-on-rails drop-down-menu


    【解决方案1】:

    首先,您应该在控制器中创建一个如下所示的哈希:

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

    注意:我在 onchange 事件中使用了标准的 Javascript,如果你使用 jQuery 或prototypeJS,这可以写得更短更简洁:)

    【讨论】:

    • 备注:如果你有国家代码的国家模型,那么你可以使用options_from_collection_for_select而不是哈希;)
    • 好评。我个人会尽可能避免手动构建选择选项
    • 这对我来说是一个很好的开始,而且效果很好。我想将国家代码 text_field_tag 设置为不可编辑的显示而不是表单。如果我使用 :disable,它不会被发送。我应该采取其他方式吗?
    • 是的,我想我会为它修一个模型。使其在以后的工作中更加通用,尤其是在约 100 个国家/地区...
    • @julien:看看readonly attribute
    【解决方案2】:

    你也可以这样做:

    <%= 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)
    

    您将此部分放入 erb 位的 html 选项中的 :onchange => "..." 中。

    我的 jQuery 可能已关闭,但您可以在 api 站点获得更好的想法。 jQuery

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多