rails 上的 Ruby - 使用 AJAX 更新输入 select 选项

Ruby on rails - update input select options using AJAX

我有这个输入的简单形式:

<%= f.input :seleced_seats, collection: @event.seats, label: "-", label_html: { style: 'visibility: hidden; height: 0px;'}, include_blank: false %>

它包含我想使用 AJAX 更新的选项。我获取输入数组 (data.seats) 的 JavaScript 是:

$("#event_seleced_seats").change(function(){
    var seleced_seats = $(this).val();  
    var seleced_term = $("*[class='list-group-item active']").attr('id');

    jQuery.getJSON(window.location.href + "/price", {edition: seleced_seats, term: seleced_term}, function(data) {
        $("#price").text(data.total_price);
        $("#termA").text(data.seats);
        console.log(data.seats);
    });
});

如何使用 data.seats 中的数据重绘 f.input?

如何清空下拉列表并添加 data.seats 和 jQuery 追加?

所以像这样:

(假设data.seats将return一个座位对象数组)

var dropDown = $(yourdropdown);
dropDown.empty();

data.seats.forEach(function(seat){
  dropDown.append("<option value='"+seat.your_value+"'>"+seat.your_value+"</option>")
});

您还可以使用 jQuery each 方法来遍历集合。 有关详细信息,请参阅 API:http://api.jquery.com/jquery.each/