繁体   English   中英

从另一个下拉列表中选择一个值后填充下拉列表

[英]Populate dropdown list upon selecting a value from another dropdown list

我试图根据我的rails项目中另一个下拉列表的选择填充一个下拉列表。 唯一的区别是两个下拉列表都应使用一个模型填充。

模型为City ,并具有名称 和州

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

id = 1
name = LOSANGELES
state = CA

我已经检查过Rails 4:如何通过AJAX根据另一个collection_select更新collection_select? 和其他链接,但我似乎无法弄清楚如何从与第一个下拉菜单相同的模型中填充城市下拉列表

这是我的代码:

controllers / 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>

任何帮助深表感谢!

更改您的city_stats方法。 此方法应返回ID和名称

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>';    
}); 

暂无
暂无

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

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