Populate a Select Dropdown List using JSON
A common requirement when developing forms on the web is populating a dropdown list using data from a web service or external file.
Suppose we have a form that asks the user for their country followed by the state or province (if applicable). We would want the country selection to determine the list of states/provinces that are displayed.
We'll walk through code that populates a dropdown using sample JSON data containing Canadian province names and abbreviations.
[{
"name": "Alberta",
"abbreviation": "AB"
},
{
"name": "British Columbia",
"abbreviation": "BC"
},
{
"name": "Manitoba",
"abbreviation": "MB"
},
{
"name": "New Brunswick",
"abbreviation": "NB"
},
{
"name": "Newfoundland and Labrador",
"abbreviation": "NL"
},
{
"name": "Nova Scotia",
"abbreviation": "NS"
},
{
"name": "Northwest Territories",
"abbreviation": "NT"
},
{
"name": "Nunavut",
"abbreviation": "NU"
},
{
"name": "Ontario",
"abbreviation": "ON"
},
{
"name": "Prince Edward Island",
"abbreviation": "PE"
},
{
"name": "Quebec",
"abbreviation": "QC"
},
{
"name": "Saskatchewan",
"abbreviation": "SK"
},
{
"name": "Yukon",
"abbreviation": "YT"
}
]
We'll use the names for the contents of the <option> elements and the abbreviation for the values.
<option value="AB">Alberta</option>
The following solutions manipulate the DOM by populating an HTML select element we've defined on our page:
<select id="locality-dropdown" name="locality">
</select>
Our task can be divided into four steps:
- Target the dropdown
- Clear any existing options
- Insert a default option named "Choose State/Province" which is shown as a visual cue
- Insert an option for each province found in the JSON data
Solution using Vanilla JavaScript
Using XMLHttpRequest
let dropdown = document.getElementById('locality-dropdown');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Choose State/Province';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = 'https://api.myjson.com/bins/7xq2x';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
const data = JSON.parse(request.responseText);
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].name;
option.value = data[i].abbreviation;
dropdown.add(option);
}
} else {
// Reached the server, but it returned an error
}
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};
request.send();
Code Breakdown:
- Line 1 targets the select element
- Line 2 clears any options in the element
- Lines 4-5 appends our default option
- Line 10 defines the URL where we can find our JSON data
- Lines 12-13 initializes the remote request
- Lines 19-24 creates an option element for each entry found and adds it to the select list
- Line 34 sends the remote request
Using Fetch API
let dropdown = document.getElementById('locality-dropdown');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Choose State/Province';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = 'https://api.myjson.com/bins/7xq2x';
fetch(url)
.then(
function(response) {
if (response.status !== 200) {
console.warn('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].name;
option.value = data[i].abbreviation;
dropdown.add(option);
}
});
}
)
.catch(function(err) {
console.error('Fetch Error -', err);
});
Key Benefits
- Dynamic Content: Dropdown options are loaded from external data sources
- Maintainable: JSON data can be updated without changing the HTML
- Scalable: Easy to add or remove options by modifying the JSON
- User-Friendly: Provides a better user experience with relevant options
This approach is particularly useful for forms that need to display location-based data, user preferences, or any dynamic content that changes based on user selections or external data sources.