选择onchange with city-state ruby​​ gem

时间:2015-09-17 00:25:03

标签: javascript html ruby-on-rails-4 onchange

我尝试使用城市状态宝石(https://github.com/loureirorg/city-state)并使用Javascript动态更新城市的选择器取决于状态选择器。

我的想法:选择状态后," 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>

1 个答案:

答案 0 :(得分:1)

您需要修改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请求。然后,在查看州代码时,它将返回属于该特定州的城市列表。 关于AJAX的成功,这些城市正在被填充。