gpt4 book ai didi

jquery - 如何在rails中通过collection_select进行ajax搜索?

转载 作者:行者123 更新时间:2023-12-01 05:31:32 24 4
gpt4 key购买 nike

我试图通过选择特定的州来显示城市。但我不知道如何使用数据“collection_select 中的选定选项”发出 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
}));
});
});
});

关于jquery - 如何在rails中通过collection_select进行ajax搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990869/

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