Select onchange with city-state ruby gem

Select onchange with city-state ruby gem

我正在尝试使用城市状态 gem (https://github.com/loureirorg/city-state) 并使 select 或城市动态更新 Javascript 取决于状态 select或.

我的想法:在 select 状态之后,"form.select :city" 将只为这个状态填充城市。

这是我的...html.erb

<%= fs.select :state_code, options_for_select(us_states), {}, class: "form-control", id: "state_code", :onchange => "javascript: state_code();"  %>

<%= fs.select :city, options_for_select(CS.get :"#city", :al), {},   class: "form-control", id: "city" %>

这是我的 Javascript:

   <script type="text/javascript">
     $("#state_code").onchange( function() {
      $("#city").val("state_code").change();
 })
</script>

您需要修改您的HTML人口和JS代码。此外,应用程序控制器中的一个操作来响应获取该州城市的请求。

---
JS
---
$(document).on('change', '#states-of-country', function(e) {
  var cities_of_state, input_state, state;
  input_state = $(this);
  cities_of_state = $('#cities-of-state');
  state = this.options[e.target.selectedIndex].id;
  if (state === 'no-state') {
    return cities_of_state.html('');
  } else {
    $.ajax({
      url: '/cities/' + $(this).children(':selected').attr('id'),
      success: function(data) {
        var opt;
        opt = '<option value="" selected>Select Your City</option>';
        if (data.length === 0) {

        } else {
          data.forEach(function(i) {
            opt += '<option value="' + i + '">' + i + '</option>';
          });
          cities_of_state.html(opt);
        }
      }
    });
  }
});
------------------------
Application Controller:
------------------------

def cities
  render json: CS.cities(params[:state], :us).to_json
end

-----------
routes.rb:
-----------
get 'cities/:state', to: 'application#cities'
-----
HTML
-----
<select id="states-of-country" name="project[state]">
  <option id="no-state" value="" selected>Select Your State</option>
  
  /* For states within US */
  <% CS.states(:us).each do |key, value| %>
    <option value="<%= value %>" id="<%= key %>"><%= value %></option>
  <% end %>
</select>
      
<select id="cities-of-state" name="project[city]" class="form-control form-control-small" required>
  <option value="" selected>Select Your City</option>
</select>
            
            
            
            

因此,当值更改时,将向服务器发出 GET 请求。然后在查看州代码时,它将 return 属于该特定州的城市列表。 在 AJAX 成功后,这些城市就会有人居住。