简体   繁体   English

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

[英]How do I turn an array of strings into a select drop down menu in a Rails/JavaScript file?

I have a menu where I select a time slot and a JavaScript function is called. 我有一个菜单,可以在其中选择一个时隙,然后调用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'
  });
})

It takes in the selected value and passes that into a controller method that prepares an array I'll need for the new select drop-down menu. 它接受选定的值,并将其传递到控制器方法中,该方法为新的select下拉菜单准备一个数组。 My aim here is to populate this new select drop-down with a list of available dates for the selected time slot. 我的目的是在此新选择下拉列表中填充所选时隙的可用日期列表。

The controller method that gets called is: 被调用的控制器方法是:

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

The available_dates_select.js.erb file is: available_dates_select.js.erb文件为:

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

Just to test, I converted the content of the array passed in from the controller to JSON, then I append it to a <div> in my view to see if it has the contents I expect. 为了进行测试,我将从控制器传入的数组的内容转换为JSON,然后将其附加到视图中的<div>以查看其是否具有我期望的内容。

View after JavaScript updates it: 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"]

What I need to do is take this array and turn it into a select drop-down. 我需要做的是将此数组转换为选择下拉列表。 In the JavaScript file then add the select menu to the view instead of the raw array. 然后在JavaScript文件中,将选择菜单而不是原始数组添加到视图中。

I tried a few snippets of code from here but none seem to work. 我从这里尝试了几段代码,但是似乎都没有用。

Would really appreciate an example to learn from. 真的很感谢一个可以学习的例子。

尝试

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

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

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