Search code examples
javascriptruby-on-railsajaxruby-on-rails-4simple-form

Ruby on rails - update input select options using AJAX


I have Simple form with this input:

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

It contains options I want to update using AJAX. The JavaScript where I get the array for the input (data.seats) is:

$("#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);
    });
});

How can I redraw the f.input with data from data.seats?


Solution

  • How about emptying your dropdown and adding the data.seats with jQuery append?

    So something like this:

    (assuming the data.seats will return an array of seat objects)

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

    You could also use the jQuery each method to loop over the collection. See the API for more information: http://api.jquery.com/jquery.each/