如何将字符串数组转换为Rails / JavaScript文件中的选择下拉菜单?

时间:2014-10-14 22:47:04

标签: javascript jquery ruby-on-rails ruby ruby-on-rails-4

我有一个菜单,我选择一个时间段并调用JavaScript函数。

$('#timeSlotSelect').on('change', function(event) {
  alert($(this).val());

  var time_slot = $(this).val();
  var i = time_slot.indexOf(' ');
  var dayFiltered = time_slot.substring(0, i);

  $.ajax({url: "/activities/get_valid_date_range", 
    data: {day: dayFiltered}, 
    type: 'POST'
  });
})

它接收所选值并将其传递给控制器​​方法,该方法准备新的选择下拉菜单所需的数组。我的目标是在这个新的选择下拉列表中填入所选时段的可用日期列表。

被调用的控制器方法是:

def get_valid_date_range
    respond_to do |format|          
        day = params[:day] # day param from javascript file
        availableDates = valid_date_range(day) # logic that works out available dates
        format.js { render :available_dates_select, :locals => { :dates => availableDates} }
    end
end

available_dates_select.js.erb文件是:

$(function() {
    alert("test")
    $("div#jo").html("<%= escape_javascript dates.to_json %>")
});

为了测试,我将从控制器传入的数组的内容转换为JSON,然后在我的视图中将其附加到<div>以查看它是否具有我期望的内容。

JavaScript更新后查看:

["14th October 2014","21st October 2014","28th October 2014","4th November 2014","11th November 2014","18th November 2014","25th November 2014","2nd December 2014","9th December 2014","16th December 2014","23rd December 2014","30th December 2014","6th January 2015","13th January 2015","20th January 2015","27th January 2015","3rd February 2015","10th February 2015","17th February 2015","24th February 2015","3rd March 2015","10th March 2015","17th March 2015","24th March 2015","31st March 2015","7th April 2015","14th April 2015"]

我需要做的是将此数组转换为选择下拉列表。在JavaScript文件中,然后将选择菜单添加到视图而不是原始数组。

我从这里尝试了一些代码段,但似乎都没有。

非常感谢一个可以借鉴的例子。

1 个答案:

答案 0 :(得分:1)

尝试

$("div#jo").html("<%= escape_javascript select_tag(:dates, options_for_select(dates)) %>")