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

Updated on May 3, 2018
timothy-malche profile image

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

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

Does this article helped you?

See results

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Ebenezer 

      7 weeks ago

      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

    • profile image

      Pascal 

      2 months ago

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

    • timothy-malche profile imageAUTHOR

      Timothy Malche 

      4 months ago from Jabalpur, M.P., India

      Hi Nidhi,

      Thanks for your comments.

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

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

    • profile image

      Nidhi Maheshwari 

      4 months ago

      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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)