Vanilla Javascript Select Feature

Eve Reichmann
Dev Genius

--

It’s nice to be able to make your application more dynamic. No one wants to have to hard code in dropdown options if they are going to be ever-growing or even something that can be pulled from a database. I am going to walk you step by step on how to render a select form field with data from a database.

  1. The Forms

Write our form as you would normally it makes it a little easier if you write your form in a Javascript file and append it. Your select files do not need to have any option tags in it, Javascript will handle that for us.

const form = (`
<form>
<input type="type"></input>
<select id="dropdown"></select>
<button type="submit">Submit</button>
</form>
`)

2. Function

We are going to write a function that handles the iteration through the API data and render the options for our select box. A quick run-through:

~we want to find the select field I personally like to find things by id.

~we want to have a default option as a placeholder

~then make a call to your API

~once we get data back we want to iterate through and for every item, in the array, we want to create an option. Just keep in mind what information you need to send back and what you want to show to the user.

function renderDropdown(){let dropdown = document.getElementById(‘dropdown’)let defaultOption = document.createElement(‘option’)defaultOption.text = “Select Image”dropdown.add(defaultOption)fetch(“http://localhost:3000/images")/.then(resp=> resp.json()).then(images=> {for(let i = 0; i < images.length; i++){let option = document.createElement(‘option’)option.innerHTML = images[i].nameoption.value = images[i].img_urldropdown.options.add(option)}})}

3.Appending it to the form

Once again we want to find where the form live if you only have one form you can querySelecter or I like to stick with ids. Once you have the form found take the form constant and .innerHTML so that the form will render to the HTML. Once it is rendered you can call the renderDropdown function.

const FormDiv = document.getElementById('form-field')
//write the form here const here
formDiv.innerHTML = form
renderDropdown()

Just remember that Javascript runs from top to bottom so you need the form before you can run the dropdown otherwise your options will be blank.

Conclusion

Javascript is tricky at first until you pick up its weird rules. Stopping and pseudocoding was the only way I could get things to work. My biggest tip is to think about how things are rendered and what order it needs to go in. Once you master that you will really love Javascript.

--

--

I am a bootcamp student at Flatiron School in the Software Engineering program.