简体   繁体   中英

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.

$('#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. 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:

$(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.

View after JavaScript updates it:

["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.

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)) %>")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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