Billy Logan Billy Logan - 4 months ago 48
Ajax Question

simple_form select collection populated by AJAX call

In my view I have a simple form with two select lists:

<%= simple_form_for @job, url: jobs_path do |f| %>
<%= f.input_field :types, as: :select, collection: @types, id 'types-select' %>
<%= f.input_field :subtypes, as: :select, collection: @subtypes %>
<% end %>


When a user selects an option from the first list, the second list below should be populated with values from the database based on the above selection.

For this reason, I am making ajax request when a user selects an option from the first list:

$('#types-select').change(function(){
$.ajax({
url: '/subtypes',
dataType: 'json',
type: 'GET',
data: {
type_id: this.value
},
success: function(data) {
console.log(data);
}
});
});


Controller looks like this:

class SubtypesController < ApplicationController
respond_to :json

def index
@subtypes = Type.find(params[:type_id]).subtypes
render json: @subtypes
end
end


At this point how can I fill up the second select with options from @subtypes?

Answer

You can populate second dropdown within success callback. Make sure @subtypes is returned in proper json format too.

Controller:

  def index
    @subtypes = Type.find(params[:type_id]).subtypes
    render json: @subtypes.map { |item| { value: item.value } }  
  end

JS:

  $.ajax({
    url: '/subtypes',
    dataType: 'json',
    type: 'GET',
    data: {
      type_id: this.value
    },
    success: function(data) {
      // Populate second dropdown here
      var output = '';
      $subtypes.empty().append(function() {
        data.forEach(function(item) {
           output += "<option>" + item.value + "</option>"
        });
        return ouput;
      });
    }
  });
Comments