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.
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
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.
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
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!