Home Programming Dynamic Dependent Dropdown in JavaScript with AJAX

Dynamic Dependent Dropdown in JavaScript with AJAX


Hello, good to see you. Are you looking for a tutorial to help you build a dynamic dependent dropdown in javascript, you are in the right place. In this tutorial, I am going to show you how you can easily create a dynamic dependent dropdown with pure javascript. Of course, we are going to use HTML for the basic structure and CSS for a bit of styling.



In this tutorial, we are going to create a project called City Explorer, which allows us to select a city by navigating through the dynamic dependent dropdown.

Firstly, I am going to break down the steps into 3 different sections:

  1. Setting up the project structure
  2. Getting the API Authorization Token.
  3. Test our work

Setting up the project structure

Our project will be a simple HTML/CSS/JS project, which uses a free API, which provides us with Countries, States, and Cities around the world in JSON format. We will use this API to fetch the data and dynamically place it in the dropdown.

1. First, create a folder and name it, say, City Explorer.

2. Then, create three files, index.html, style.css, script.js.

3. Create another folder in the city explorer folder and name it “img”. Place this image in the img folder

4. Now open any code editor and paste the below code. Don’t worry, I will explain the code thoroughly.

5. Copy the code given below and paste accordingly in index.html , script.js , and  style.css.

Getting the API Authorization Token

1. Goto to www.universal-tutorial.com

2. Then, under Generate Token, enter name and email and submit.  Next, you will get a generated token, like this
Generated Token : Z6axeG_6lIk1sqo7Zh8PnRxpwBylqrCqJEjTdZBF9Onb8Om82M3Ms5lzi26U8KtNXRQs

Dynamic Dependent Dropdown

Copy and keep this token safely as you are gonna need it to generate an authorization token for the API endpoint.

3. Then open the index.html file on a browser like Google Chrome >> Right-click and select Inspect element >> Goto Console.

4. Then, type and execute the function getAccessToken(email,token). Pass the email you used while generating the token and the generated token itself as arguments to the getAccessToken() function.

5. As a result, you will get an authorization token, which you need for consecutive API calls.

Dynamic Dependent Dropdown

Now you have the API auth_token let’s put it on our code and test our work.

Finally testing our work

1. Now open the script.js file and replace the auth_token with the one you got on the earlier steps.

2. Now open the index.html file and then check the input, it will dynamically update, you can test that by selecting different options.

Github: https://github.com/mintukurmi/CityExplorer/

I hope you followed the tutorial and were able to get it. If in case you didn’t understand some part of it. Let me know in the comments below.



Please enter your comment!
Please enter your name here