How to Add Options from a JSON File to a Select Dropdown
In this tutorial, we will learn how to load a list of options in a JSON file and add them to a select dropdown. This method will also work with jQuery UI select dropdowns.
The JSON Data
We will be using JSON data which contains an array of objects that have two properties; a country name and a dialling code.
/js/country_codes.json
[
{ "country": "United Kingdom", "code": "44" },
{ "country": "United States of America", "code": "1" },
{ "country": "Australia", "code": "61" },
{ "country": "Canada", "code": "1" }
]
The Function
Let's create a function that will load a list of country codes from a JSON file using the jQuery getJSON()
method, loop through the codes and add them to a select dropdown.
function set_country_codes() {
var filePath = '/js/country_codes.json';
$.getJSON(filePath, function( data ) {
$.each( data, function( key, val ) {
$('#code').append('<option value="+'+ val['code'] +'">'+ val['country'] +'</option>');
});
});
}
set_country_codes();
Setting a Selected Option
To set a selected option when adding options to a select dropdown, add some ternary logic to look for a value and add a selected attribute to the option.
function set_country_codes() {
var filePath = '/js/country_codes.json';
$.getJSON(filePath, function( data ) {
$.each( data, function( key, val ) {
let selected = val['code'] == '44' ? 'selected' : '';
$('#code').append('<option value="+'+ val['code'] +'" '+selected+'>'+ val['country'] +'</option>');
});
});
}
set_country_codes();
jquery