简体   繁体   中英

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?

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/

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