❮ 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);
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()YesYesYesYesYesSyntax
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 listTechnical Details
Return Value:No return valueMore 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]);
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]);
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);
}
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 TableThis 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:
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 fileYou 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 title="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 DemoExample-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 DemoExample-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 DemoConclusion
In this article, you have seen programmatically create a dropdown list using JavaScript from the JSON data format.