【发布时间】:2018-08-21 13:36:53
【问题描述】:
我在 Rails 中遇到了选择选项的问题。在更改状态时,应该附加城市选项,但这对我不起作用。请帮帮我,那做错了什么
这就是我所做的: 在我的 _form.html.erb 文件中:
<div class="form-group col-md-6">
<!-- State -->
<%= label_tag "Shop address" %>
<%= select_tag :pstate, options_for_select(CS.states(:in).map { |c| [c[1], c[0]] }), class: "form-control", :required => true, :onchange => "stateChanged(event)" %>
</div>
<div class="form-group col-md-6">
<!-- City -->
<%= label_tag "Shop location" %>
<%= select_tag :pcity, options_for_select([@pcities]), class: "form-control", :required => true %>
</div>
</div>
<script>
var stateChanged = function(e){
$.ajax({
url: "products/product_cities?state=" + e.target.value,
type: "GET"
})
}
</script>
并且在 products_controller.rb 文件中
def product_cities
@pcities = CS.get(:in, params[:state])
puts @pcities.inspect
end
在 products_cities.js.erb 文件中
<%# // Find the state select box %>
var city = document.getElementById("pcity");
console.log(city);
<%# // Clear the options in the select box %>
while (city.firstChild) city.removeChild(city.firstChild);
<%# // Add a placeholder %>
var placeholder = document.createElement("option");
placeholder.text = "Choose a city";
placeholder.value = "";
city.appendChild(placeholder);
<%# // Add the cities %>
<% @pcities.each do |c| %>
city.options[city.options.length] = new Option('<%= c %>');
<% end %>
请你帮我摆脱困境。
【问题讨论】:
标签: javascript ruby-on-rails ruby-on-rails-5