【问题标题】:Populate dropdown list upon selecting a value from another dropdown list从另一个下拉列表中选择值时填充下拉列表
【发布时间】:2017-09-27 15:26:44
【问题描述】:

我正在尝试根据在我的 rails 项目中选择的另一个下拉列表来填充一个下拉列表。唯一的区别是两个下拉列表都应该从一个模型中填充。

模型是City,它有namestate

name 是城市名称,state 是城市所属的州。 例如,一个城市对象是:

id = 1
name = LOSANGELES
state = CA

我已经检查过Rails 4: How to update a collection_select based on another collection_select through AJAX? 和其他链接,但我似乎无法弄清楚如何从与第一个下拉列表相同的模型中填充城市下拉列表

这是我的代码:

控制器/city_stats_controller.rb:

def city_stats
@state = params[:state]
@cities = City.select(:name).all.where(:state => state)

 respond_to do |format|
   format.json  { render :json => @cities }      
 end
end

views/city_stats/city_stats.html.erb:

<div class="row">
    <label>State <span>*</span></label>
    <%= collection_select :city, :state, City.select(:state).uniq.order('state ASC'), :id, :state, {:prompt => 'Select a State'}, {id: 'state', multiple: false} %>

    <label>City <span>*</span></label>
    <%= collection_select :city, :name, [], :id, :name, {:prompt => 'Select a City'}, {id: 'name', multiple: false} %>
</div>

<script type="text/javascript">
$(document).ready(function() {
$("#state").on('change', function(){
  $.ajax({
    url: "/admin/city_stats",
    type: "GET",
    data: {state: $(this).val()},
    success: function(data) {
      $("#city").children().remove();
      // Create options and append to the list
      var listitems = []; 
      $.each(data,function(key, value) { 
        listitems += '<option value="' + key+ '">' + value + '</option>';    }); 
    $("#city").append(listitems);
    console.log(listitems);
     }
    })
  });
});
</script>

非常感谢任何帮助!

【问题讨论】:

  • 有什么问题?您遇到任何错误吗?哪部分代码不起作用?
  • @krishnar 我没有收到任何错误,只是我从第一个下拉列表中选择某个州后,城市下拉列表没有填充
  • 当状态下拉值改变时您是否收到请求?
  • 检查我的解决方案。我认为这对你有用

标签: javascript jquery ruby-on-rails drop-down-menu


【解决方案1】:

改变你的 city_stats 方法。这个方法应该返回 id 和 name

def city_stats
  @state = params[:state]
  @cities = City.where(:state => state).select(:id, :name)

  respond_to do |format|
   format.json  { render :json => @cities }      
  end
end

像这样在 ajax 调用中更改每个函数。因为响应的数据是我们使用的对象数组 value.id, value.name 。

$.each(data,function(key, value) { 
  listitems += '<option value="' + value.id + '">' + value.name + '</option>';    
}); 

【讨论】:

  • 我不确定我是否得到了您的答案。我认为您混淆了控制器中的操作名称,即 (city_stats) 而不是 city_state。第一个选择的 id 是 state,而第二个选择的 id 是 city
  • id 应该是列本身的名称吗?比如第一个 collection_select 的 id 是 state,第二个是 name?
  • @GeoSal 每当你改变状态时是否命中服务器?
  • 我的意思是每当你改变状态时,你能在 rails c 中看到请求吗?你得到的回应是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多