自定义国家/州下拉列表

时间:2016-02-20 21:03:01

标签: javascript ruby-on-rails countries

有些日子我曾在国家和州/省选择的宝石上挖掘过。有些很棒(如country-state-select)但不符合我的需要。

几乎强制性的country_select宝石很好,但缺乏状态。然而,这是基于这个非常酷的宝石countries。宝石国家真的汇集了很多好的信息,比如说Mozambique及其subdivisions等等,超过300个国家,包括i18n。

在应用中拥有国家/地区宝石,所有需要的是一些javascript与它进行交互。打电话是这样的:

country = ISO3166::Country.new('US')

以下是表格:

<%= simple_form_for(@order) do |f| %>
<div><%= f.input :country %></div>
<div><%= f.input :state %></div>
<%= f.button :submit, t('.submit') %>
<% end %>

<script type="text/javascript">
states_drop_down = $("#order_state");
$("#order_country").change(function() {

// How to make this work?
    <% unless params[:country].nil? %>
        states_drop_down.clearAttributes();
        <% ISO3166::Country.new(params[:country]).states.each do |state| %>
            states_drop_down.setAttribute(<%= state[:name] %>, <%= state[:alpha2] %>); // How to log to check if new attributes are present?
        <% end %>
        states_drop_down.reload(); // How to reload the state simple_form input?
    <% end %>
});

目标是众所周知的,每次国家/地区下拉列表更改时,使用正确的国家/地区填充州选择器。有帮助吗?感谢。

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,即使不再使用宝石国家了。数据被播种到数据库并从那里拉出来。找到了数据here

然后只需几步就可以了:

// 1. new action at controller, in my case was orders. This receives the calls and renders the views.
  def update_states
      country = Country.find(params[:nation_id])
      @states = country.states
      respond_to do |format|
        format.js
      end   
  end

// 2. new get at routes to find the new action
  get "orders/update_states", as: "update_states"

// 3. simple_form with collections. Note uses nation to avoid the simple_form country selector error.
  <%= simple_form_for(@order) do |f| %>
  <div><%= f.input :nation, collection: @countries %></div>
  <div><%= f.input :state, collection: @states %></div>
  <%= f.button :submit, t('.submit') %>
  <% end %>

// 4. new doc at app/views/states/_state.html.erb to render inside the dropdown selector.
  <option value="<%= state.id %>"><%= state.name %></option>

// 5. new lines at app/assets/javascripts/orders.js.coffee to listen to nation or country selector.
  $ ->
  $(document).on 'change', '#order_nation', (evt) ->
  $.ajax 'update_states',
  type: 'GET'
  dataType: 'script'
  data: {
    nation_id: $("#order_nation option:selected").val()
  }
  error: (jqXHR, textStatus, errorThrown) ->
    console.log("AJAX Error: #{textStatus}")
  success: (data, textStatus, jqXHR) ->
    console.log("State selection is working!")

// 6. and app/views/orders/update_cities.js.cofee, the piece that close the circle. This actually renders the info and views.
  $("#order_state").empty()
  .append("<%= escape_javascript(render(:partial => @states)) %>")

一定要感谢Kernel Garden,我找到了我正在寻找的javascript here