Reputation: 37
{"BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria"}
How could I display this data as options in select box in html using javascript?
Upvotes: 0
Views: 2022
Reputation: 14531
Here's a way of solving the problem without jQuery, and without appending the HTML strings. I am using the Option
constructor to create an option in the drop-down menu and inserting that into the select
element.
var data = {"BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria"};
var selectControl = document.getElementById("countries");
for(var prop in data) {
if(data.hasOwnProperty(prop)) {
var option = new Option();
option.text = data[prop];
option.value = prop;
selectControl.options[selectControl.options.length] = option;
}
}
<select id="countries">
</select>
Upvotes: 0
Reputation: 1088
Iterate over your array with let country of countries and add your info as text and value to your select drop-down. Text would be the abbreviation such as BE and value would be Belgium.
Upvotes: 0
Reputation: 30739
It is very simple if you use with Javascript. Do this,
var countries = {"BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria"};
var selectHTML='';
for (var key in countries)
{
selectHTML +='<option value="'+key+'">'+countries[key]+'</option>';
}
document.getElementById('countries').innerHTML = selectHTML;
<div id="select_box_wrapper">
<select id="countries"></select>
</div>
Upvotes: 2