Dynamically Generate Attributes for Options in Select Drop Downs — Javascript

Amanda Walker Brubaker
3 min readDec 2, 2020

--

Photo Credit: Gregory Dubus

When creating a dog walking SPA with JavaScript, I came across the need to create a drop down menu to select which dog the walk request is for. Since owners can have more than one dog, I wanted a way to dynamically create this using the array of the owner’s dogs. After scouring the internet for a solution, I thought I would put my findings here in the hopes it helps the next coder!

A non-dynamic drop down option for a dog’s gender.

Opinion: I personally like to have the top option blank, so that when the form loads, it doesn’t pre-generate one of the values for you.

Now how would I generate the option tags if I had an array of information? Below I wanted the text shown to be the dog’s name, but the value to be the dog’s id, so it would be associated with that dog’s instance once it was persisted to the database. My array contains instances of each dog an owner has, so I am able to access that dog’s name and id.

In order to dynamically create an option for each dog, I mapped through the dog array and returned an option tag that contained the dog’s id as well as its name.

A dynamically generated drop down menu.

If you look closely above, along with the option tags being generated, you’ll notice a handleChange event. I use this to keep track of my state any time the user changes any input on the form.

For each selection within the form, I set up a name and value property for each section of the form (e.g. date of appointment, time, address, dog, etc). Rather than calling each of these manually, I generated an abstract handleChange function where I set the local states’ key value pairs. This is both clean and simple — my favorite kind of code whenever possible!

An abstract handleChange function.

I hope this was helpful, and I will definitely be referencing this post int he future the next time I need to create a dynamic drop down. Please feel free to ask any questions!

Keep well and code on.

--

--

Amanda Walker Brubaker
Amanda Walker Brubaker

No responses yet