0

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?

1 Answer 1

3

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;
      });
    }
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.