Updated date:

How to Populate Values in One HTML Dropdown List With Another Using Simple Javascript

Timothy is an enthusiast programmer and loves developing websites. He is expert in HTML, CSS, JavaScript, PHP, C#, and ASP[dot]NET.

how-to-control-values-displayed-in-one-html-dropdown-list-with-the-other-using-simple-javascript

1. Introduction

HTML Dropdown Lists play an important role in a Web Form when we want to gather some user information. Dropdown Lists takes very small space on a page while allowing to specify large volume of information from which user may select an option.

So let’s start with our task. Before we begin just remember one thing that I am using Bootstrap library in my code for styling HTML elements. If you don’t know how to use Bootstrap, follow the link given below:

2. Create Dropdown ListBox

HTML provides <select> tag to create Dropdown List. In fact using <select> tag you can create following types of HTML list controls

  • Dropdown List (By Default)
  • List Box (By adding size attribute)

The following code creates two list box named 'firstList' and 'secondList'. At this point I have not specified any value to be displayed on lists because I’ll be using JavaScript to populate them. Also note 'onClick' attribute in 'firstList'. Whenever user click on the one of element in 'firstList', the function will fire. The explanation of what function does is explained in the next section.

<body>
	<div class="col-md-4">
	<form>
	<h4>Food Type</h4>
	<select class="form-control"  id='firstList' name='firstList' onClick="getFoodItem()">
	</select>
	
	<h4>Food Item</h4>
	<select class="form-control"  id='secondList' name='secondList' >
	</select>
	
	</form>
	</div>
</body>

When you run code after adding just above piece of code, the output will look like following

Output of HTML code with empty Lists

Output of HTML code with empty Lists

3. Populate Lists

Our next step is to populate these lists using the following piece of JavaScript code.

If you don’t know how to add JavaScript to HTML page, follow the link below

		$(document).ready(function () {
		
		var list1 = document.getElementById('firstList');
	
		list1.options[0] = new Option('--Select--', '');
		list1.options[1] = new Option('Snacks', 'Snacks');
		list1.options[2] = new Option('Drinks', 'Drinks');
		});

In the code I have used following function

$(document).ready(function () {

...

 }) ;

This function is required because it automatically fire the JavaScript code on page load. We need this function in our code since we want to populate the drop-down list 'firstList' automatically whenever page is displayed to user.

In the function I have written the code to add values to 'firstList'. For this you first need to identify the control which can be done using following code:

var list1 = document.getElementById('firstList');

and then using Option class of JavaScript add values to 'firstList'

list1.options[0] = new Option('--Select--', '');
list1.options[1] = new Option('Snacks', 'Snacks');
list1.options[2] = new Option('Drinks', 'Drinks');

the next part of JavaScript code is 'getFoodItem()' function. This function is linked to drop-down list 'firstList' using the 'onClick' attribute. So whenever a user perform a click operation on 'firstList', it will invoke 'getFoodItem()' function.

'getFoodItem()' function populates the drop-down list 'secondList' on the bases of condition specified in the code.

For example, in this tutorial, if user selects ‘Snacks’ option from firstList, the secondList is populated with options for available ‘Snacks’ such as ‘Burger’, ‘Pizza’, ‘Hotdog’ etc.

The code for function given below:

function getFoodItem(){

			var list1 = document.getElementById('firstList');
			var list2 = document.getElementById("secondList");
			var list1SelectedValue = list1.options[list1.selectedIndex].value;
			
			if (list1SelectedValue=='Snacks')
            {
				
				list2.options.length=0;
				list2.options[0] = new Option('--Select--', '');
				list2.options[1] = new Option('Burger', 'Burger');
				list2.options[2] = new Option('Pizza', 'Pizza');
				list2.options[3] = new Option('Hotdog', 'Hotdog');
				list2.options[4] = new Option('Potato Chips', 'Potato Chips');
				list2.options[5] = new Option('French Fries', 'French Fries');
				
			}
			else if (list1SelectedValue=='Drinks')
            {
				
				list2.options.length=0;
				list2.options[0] = new Option('--Select--', '');
				list2.options[1] = new Option('Coca Cola', 'Coca Cola');
				list2.options[2] = new Option('7up', '7up');
				list2.options[3] = new Option('Pepsi', 'Pepsi');
				list2.options[4] = new Option('Coffee', 'Coffee');
				list2.options[5] = new Option('Tea', 'Tea');
				
			}
}

Point to note

Please note that full code for both the functions i.e. '$(document).ready(function () { ...})' and function 'getFoodItem() { ... }' must be placed inside the tags.

the following code identify controls in page, as we have also done earlier

var list1 = document.getElementById('firstList');
var list2 = document.getElementById("secondList");

next line of code extracts the value from drop-down list 'firstList', i.e. ‘Snacks’, or ‘Drink’ based on selection

var list1SelectedValue = list1.options[list1.selectedIndex].value;

after this the condition is checked . On the basis of condition the value is added to 'secondList'.

I have also added the following line of code to clear 'secondList' before adding value to it each time.

This is required because if it is not done than the value will be appended to 'secondList' each time and its data will simply grow and as a result inconsistent information will be displayed

list2.options.length=0;

Point to note

In the Option class for adding values to both the lists, two strings are specified. The first string is specified to display value to user and second is specified for value to be used by code to display it in alert box or to store it in database.

the general syntax is following

'new Option(String1, String2);'

When you run the final code, the output will be displayed as following

Final Output after adding JavaScript

Final Output after adding JavaScript

Now select any item from 'firstList'

Item 'Snacks' selected from firstList

Item 'Snacks' selected from firstList

The 'secondList' will display values for the item selected in 'firstList'

The secondList populated with 'Snacks' options

The secondList populated with 'Snacks' options

Comments

Chimma Kumar on June 29, 2020:

Hi,

This is Kumar, I am doing presently payment form, In that i want to display amount based on two drop down input values, If i select course value and level value i need to display the amount. Please check below code and kindly suggest.

Lee Lyans on October 31, 2019:

Can we please get a zip of that page so we could use it.

Please provide the link

Timothy Malche (author) from Jabalpur, M.P., India on May 14, 2019:

Hi Rod, thanks. Plz see another article on this in the following link. Hope it helps.

https://discover.hubpages.com/technology/How-to-Po...

Rod Weston on May 14, 2019:

I used your excellent article in a form I am building. It worked great. But when I load the page from the database, it doesn't display the values I retrieved from the database. What do I need to do to make this happen?

Shripad on April 27, 2019:

I am trying to run your code. The first dropdown box becomes default --select -- after the click also. Though it populates the second dropdown menu

Afolayan Toluwalope on April 17, 2019:

Good day sir, u really did a great and wonderful job here sir, but please sir i have a concern, how so i add a search option to the dropdown list if i have a very lengthy list and i do not want my user to start scrolling through a long list. i have tried with the current code but it is not populating the list when i view them on the browser. Please help sir. thanks

bhavna rathod on March 26, 2019:

Thanks this code is helpfull for me.but next step i want to multiple dropdown same display.

rehager on March 12, 2019:

This was amazingly helpful! Thank you.

Ebenezer on October 20, 2018:

Hi Sir, i have an html with a drop down list that contains a list of drinks and i want to link that to javascript such that when a user selects a particular drink, price of the drink will automatically pop up

Pascal on September 26, 2018:

Thanks...but can you add the full code. it would be helpful.

Timothy Malche (author) from Jabalpur, M.P., India on August 10, 2018:

Hi Nidhi,

Thanks for your comments.

For your query regarding multiple selection please visit my other article on following link

https://discover.hubpages.com/technology/Multiple-...

Nidhi Maheshwari on August 04, 2018:

Hi,

Thanks for your post.

It is really helpful.

I want to implement the same with slighter modification.

If user select both snacks and drinks, that is multiple options from first dropdown, second dropdown should show options available in both snacks and drinks. Can you please help me with same. Thanks.