How to create select option dynamically in JavaScript?

❮ Select Object

Example

Add a "Kiwi" option at the end of a drop-down list:

var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);

Try it Yourself »


Definition and Usage

The add() method is used to add an option to a drop-down list.

Tip: To remove an option from a drop-down list, use the remove() method.


Browser Support

Methodadd()YesYesYesYesYes

Syntax

selectObject.add(option, index)

Parameter Values

ParameterDescriptionoptionRequired. Specifies the option to add. Must be an option or optgroup elementindexOptional. An integer that specifies the index position for where the new option element should be inserted. Index starts at 0. If no index is specified, the new option will be inserted at the end of the list

Technical Details

Return Value:No return value

More Examples

Example

Add a "Kiwi" option at the beginning of a drop-down list:

var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[0]);

Try it Yourself »

Example

Add a "Kiwi" option at index position "2" of a drop-down list:

var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option, x[2]);

Try it Yourself »

Example

Add an option before a selected option in a drop-down list:

var x = document.getElementById("mySelect");
if (x.selectedIndex >= 0) {
  var option = document.createElement("option");
  option.text = "Kiwi";
  var sel = x.options[x.selectedIndex];
  x.add(option, sel);
}

Try it Yourself »


❮ Select Object

In this How-To we’ll explore how to dynamically add new options to an HTML drop-down, or in other words, how to add new <option> elements to a <select>.

This can be useful if you have a variable number of things to show as a selection to a user. For example, choosing a color or a size for a t-shirt, selecting a batch size for a print job, a format for a printed picture, etc.

Method 1: Using data from a Detail Table

This is the simplest method, as it only needs a simple loop going through the table and adding the elements as it goes. We’ll assume the data does not need to be filtered, since that should be done in whatever data source you’re using.

Let’s imagine we have a <select> element with the ID of tshirtsize, and we have the following table somewhere in our data model:

How to create select option dynamically in JavaScript?

The script to add all 6 sizes to the drop-down would be the following (with the selector being #tshirtsize ):

var sizes = record.tables.sizes;
for each (size in sizes) {
	results.append('<option value="'+size.fields.tag+'">'+ size.fields.display + ' (' + size.fields.price + ')' +'</option>');
}

The  function adds the HTML string containing the new value inside of the <select>, at the end of all the existing options, so in this case the entries in the drop-down are added in the same order they are found in the detail table.

Method 2: Loading from a JSON source file

You might have realized from some other how-tos and training material, we kind of love JSON. This format makes it pretty simple to exchange just a bunch of strings in a specific structure defined by… well, you.

So let’s take the following JSON structure, similar to the data model above, in a snippet called “sizes.json”:

Get full access to jQuery and JavaScript Phrasebook and 60K+ other titles, with free 10-day trial of O'Reilly.

There's also live online events, interactive content, certification prep materials, and more.

In real-time web applications, sometimes we are required to create a dynamic select drop-down list (combo box) which means the options will be loaded at run time for that combo box. This article shows you to create a drop-down list dynamically using JavaScript, HTML, and JSON. Here we will see multiple examples to dynamically populate select options in JavaScript.

Table of Contents

Overview

To create a dynamic drop-down combo or drop-down list, let’s assume we have a dynamic JSON array that contains the country list data (code, name) as follows:

[{
	"code":"AU",
	"name":"Australia"
},{
	"code":"FR",
	"name":"France"
},{
	"code":"IN",
	"name":"India"
},{
	"code":"JP",
	"name":"Japan"
},{
	"code":"CH",
	"name":"Switzerland"
},{
	"code":"GB",
	"name":"United Kingdom"
},{
	"code":"US",
	"name":"United States"
}]

Create a dynamic drop-down list on button click in Javascript.

To create a drop-down list dynamically on button click, we will see here multiple examples based on the country data formats. For all the examples we will have the common HTML code only Javascript code will change.

HTML CODE

<button onclick="dynamicDropdownList()">Create Dynamic Dropdown List</button>	
<br><br>
<!-- container to load dynamic dropdown list -->
<div id="dropdown-container"></div>

Example-1.

Let’s assume we have country data in the form of a string array as follows:

var countries = ["Australia","France","India","Japan","United States"];

Let’s see the javascript code for this as follows:

<script>
//country data in string array format
var countries = ["Australia","France","India","Japan","United States"];

//This method calls on button click
function dynamicDropdownList(){

	var dropdown = document.createElement("select");
	for(var i=0;i<countries.length;i++){		
		var opt = document.createElement("option"); 
		opt.text = countries[i];
		opt.value = countries[i];
		dropdown.options.add(opt);		
	}
	
	//Load the dynamically created dropdown in container
	var container=document.getElementById("dropdown-container");
	container.appendChild(dropdown);
}

</script>

See Live Demo

Example-2.

Let's assume we have country data in the form of a JSON array as follows:

var countries = [{
	"code":"AU",
	"name":"Australia"
},{
	"code":"FR",
	"name":"France"
},{
	"code":"IN",
	"name":"India"
},{
	"code":"JP",
	"name":"Japan"
},{
	"code":"CH",
	"name":"Switzerland"
},{
	"code":"GB",
	"name":"United Kingdom"
},{
	"code":"US",
	"name":"United States"
}];

Then we can write the javascript code for this as follows:

<script>
//country data in json array format
var countries = [{
	"code":"AU",
	"name":"Australia"
},{
	"code":"FR",
	"name":"France"
},{
	"code":"IN",
	"name":"India"
},{
	"code":"JP",
	"name":"Japan"
},{
	"code":"CH",
	"name":"Switzerland"
},{
	"code":"GB",
	"name":"United Kingdom"
},{
	"code":"US",
	"name":"United States"
}];

//This method calls on button click
function dynamicDropdownList(){

	var dropdown = document.createElement("select");
	for(var i=0;i<countries.length;i++){		
		var opt = document.createElement("option"); 
		opt.text = countries[i].name;
		opt.value = countries[i].code;
		dropdown.options.add(opt);		
	}
	
	//Load the dynamically created dropdown in container
	var container=document.getElementById("dropdown-container");
	container.appendChild(dropdown);
}      

</script>

See Live Demo

Example-3.

In this example, we will take the above JSON array only, but here we will write a different javascript logic to create a dynamic drop-down list.

<script>
//country data in json array format
var countries = [{
	"code":"AU",
	"name":"Australia"
},{
	"code":"FR",
	"name":"France"
},{
	"code":"IN",
	"name":"India"
},{
	"code":"JP",
	"name":"Japan"
},{
	"code":"CH",
	"name":"Switzerland"
},{
	"code":"GB",
	"name":"United Kingdom"
},{
	"code":"US",
	"name":"United States"
}];

//This method calls on button click
function dynamicDropdownList(){
	var dropdownHTML = '<select>';
	for(var i=0;i<countries.length;i++){
		var name = countries[i].name;
		var value = countries[i].code;
		dropdownHTML+='<option value="'+value+'">'+name+'</option>';
	}
	dropdownHTML+='</select>';		
	//Load the dynamically created dropdown in container
	var container=document.getElementById("dropdown-container");
	container.innerHTML=dropdownHTML;
}      
 

</script>

See Live Demo

Conclusion

In this article, you have seen programmatically create a dropdown list using JavaScript from the JSON data format.

How to dynamically add options to an existing select in JavaScript?

To dynamically add options to an existing select in JavaScript, we can use a new Option object append it to the select element with the options.add method. to add a select element.

How to add a select element?

to add a select element. to select the select element with document.querySelector. Then we call select.options.add with the Option instance to add the option. We pass in the option text and the value of the value attribute respectively to the Option constructor.

How to interact with select>option in JavaScript?

We use the HTMLSelectElement type for interacting with <select>option in JavaScript. The HTMLSelectElement type contains the following helpful attributes: selectedIndex- This attribute gives a zero-based selected options index. The selectedIndex will be -1 when no option is chosen.

How to add options to an HTML select box with JavaScript?

This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript daySelect = document.getElementById ('daySelect'); daySelect.options [daySelect.options.length] = new Option ('Text 1', 'Value1'); This suggestion managed to get my text to display properly whereas the other suggestions for some reason could not.

How do I create a dynamic select option?

To add a dropdown list dynamically, you would need to create the HTML <select> element, its label and optionally a <br> tag. In pure JavaScript, you can use the document. createElement() method to programmatically create a dropdown list. Then you can call the Node's appendChild() method or jQuery's .

How to set selected value of dropdown in JavaScript dynamically?

Get selected value from dynamic dropdown (options generated by javascript to ID).
var subjects = document. getElementsByTagName("select"). getElementById('selectSubject'). ... .
var e = document. getElementById("selectSubject"); var selected_value = e. ... .
var e = document. getElementById("selectSubject"); var selected_value = e..

How to create select options in JavaScript?

const text = selectBox. options[1]. text; const value = selectBox..
<! ... .
<html>.
<head>.
<title>JavaScript Selected Box</title>.
<link href="css/selectbox. ... .
</head>.

How to add select option value in jQuery dynamically?

The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection.