gpt4 book ai didi

javascript - 带 rails 的自定义国家/州下拉菜单

转载 作者:行者123 更新时间:2023-11-27 23:19:17 34 4
gpt4 key购买 nike

这几天我一直在挖掘 gem 以供国家和州/省选择。有些很棒(例如 country-state-select ),但不适合我的需要。

几乎是强制性的country_select gem 很好,但缺乏状态。尽管如此,它还是基于这个非常酷的 gem ,名为 countries 。 gem 国家确实汇集了很多好信息,可以说 Mozambique及其 subdivisions等,适用于 300 多个国家/地区,包括 i18n。

应用程序中有国家 gem,只需要一些 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 %>
});

目标是已知的,即每次国家/地区下拉列表发生变化时,都用正确的国家/地区填充州选择器。有什么帮助吗?谢谢。

最佳答案

我找到了一个解决方案,尽管不再使用 gem 国家。数据被植入数据库并从那里提取。查到数据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)) %>")

必须感谢内核花园,我找到了我正在寻找的javascript here .

关于javascript - 带 rails 的自定义国家/州下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528980/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com