Dynamically Populating a Form From Drop-down Selection

Recently I was working on a project that was eventually supposed to culminate in creating a form where the drop-down option selected would result in the form fields being populated with previously saved data. I thought I’d try my hand at building out that action. I’ll go into the details and code of how it works below.

Here’s the form with the options you can select.

Drop-down Menu

When you’ve made your selection some of the form fields will populate with text as you can see here.

In order to create this ability, I wrote a method in the controller that responds with the data I need in JSON format. This is useful because jQuery has an ajax function called .getJSON, which will be used later. So the method I wrote looked something like this.

1
2
3
4
5
6
7
def update_chosen_response
  @response = Response.find_by_name(params[:name])

  respond_to do |format|
    format.json { render json: @response.to_json }
  end
end

The route needs to be changed so the we can query the database by name and not just id. We do that by adding the :name to the route so we’ll have that information in the params for use later.

1
match 'update_response/:name' => 'response#update_chosen_response', :as => 'update_chosen_response', :via => :get

Now we have a method that pulls the data we need (specifically the response subject and message) and outputs it in JSON. We also have a route that allows us to pass the name of the response selected through params so we can pull the correct data. Now we can move onto the jQuery.

1
2
3
4
5
6
7
8
$('#response_category').change(function() {
  var option = $('#response_category').val();
  $.getJSON('/manage/update_response/' + option, function(data) {
    $('#response_subject').val(data.subject);
    $('#response_body').val(data.message)
  })
  return false;
});

The first line of code is a change event for when an option is selected from the drop-down menu. The second line defines the variable that is used in the next line to pass the option name to params. You’ll see the .getJSON method I mentioned earlier, which we use here to call the update_chosen_response method. Then just specify the form fields that will be affected and use .val to pass along the returned data that will populate them.

Hopefully this was helpful!