繁体   English   中英

如何在rails中通过collection_select进行Ajax搜索?

[英]How do I make a ajax search by collection_select in rails?

我正在尝试通过选择特定州来显示城市。 但是我不知道如何使用数据“ collection_select中的selected选项”发出ajax请求。

form 

%= form_for @college do |f| %>
<div class="form-group">

    <%= f.label "Select state"%>
    <%= f.collection_select(:state_id, @state, :id, :state,  {},  {class: "form-control", :id => "state_select"})%>
</div><br>
  <div class="form-group">
    <%= f.label :city_id, "Select city"%>
    <%= f.collection_select(:city_id, @city, :id, :city,  {},  {class: "form-control", :id => "city_select"})%>
</div><br>
<div class="form-group">
    <%= f.label :college, "college Name"%>
    <%= f.text_field :college, class: "form-control", placeholder: "Enter college name", required: true%>
    <br>
</div>
<div class="form-group">
    <%= f.submit class: "btn btn-primary"%>

</div>
<% end %>

 Controller for update
 def update_cities
 @cities = City.where("state_id = ?", params[:state_id])
 respond_to do |format|
  format.js
 end
 end

 JS incomplete

 $('#state_select').on('change', function(){
 $('#city_select').value.empty;
 })

您需要进行ajax调用并通过javascript进行填充。

$('#state_select').on('change', function(){
    $.ajax({
      url: "/update_cities",
    })
    .done(function(data) {
       $.each(data, function (i, item) {
        $('#city_select').append($('<option>', { 
            value: item.value,
            text : item.text 
        }));
       });
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM