How can I populate a dropdown list in JavaScript with JSON data from a file?

I am experiencing difficulties when it comes to parsing JSON files for use in a dropdown list.

JSON:

{
"BD": "Bangladesh",
"BE": "Belgium",
"BF": "Burkina Faso",
"BG": "Bulgaria",
"BA": "Bosnia and Herzegovina"
}

The goal is to populate the dropdownlist with values as shown below: Example:

<select name="optCountry" id="opt_country">
   <option value="BD">Bangladesh</option>
   <option value="BE">Belgium</option>
   <option value="BF">Burkina Faso</option>
   <option value="BG">Bulgaria</option>
   <option value="BH">Bosnia and Herzegovina</option>
</select>

Answer №1

Explore JSON.parse() to convert a json string to an Object and try using Object.keys() for separating key values into an array. Then, use Array#forEach to iterate through the key values.

var a = '{"BD": "Bangladesh","BE": "Belgium","BF": "Burkina Faso","BG":"Bulgaria","BA": "Bosnia and Herzegovina"}'
var obj = JSON.parse(a);
var select = document.createElement('SELECT')
select.name="optCountry" 
select.id="opt_country"
document.body.appendChild(select)

Object.keys(obj).forEach(function(a){
document.getElementById('opt_country').innerHTML +='<option value="'+a+'">'+obj[a]+'</option>'
})

Answer №2

Here's a suggestion for you to try out: Assuming that your JSON data is stored in a variable called data:

const dropdown = document.getElementById("country_select")
dropdown.innerHTML = "" // Clear the dropdown list
Object.getOwnPropertyNames(data).forEach(function(key){
    dropdown.innerHTML += '<option value="'+key+'">'+data[key]+'</option>'
})

Answer №3

Take your JSON data and loop through it using the method Object.prototype.hasOwnProperty(). Create an option group for each item in the JSON and then add it to a select element by updating its innerHTML attribute with the new options.

var json = '{"BD": "Bangladesh","BE": "Belgium","BF": "Burkina Faso","BG":"Bulgaria","BA": "Bosnia and Herzegovina"}';
var data = JSON.parse(json);
var result='';
for (var property in data) {
    if (data.hasOwnProperty(property)) {
result+='<option value="'+property+'">'+data[property]+'</option>';
    }
}
document.getElementById('opt_country').innerHTML=result;
<select name="optCountry" id="opt_country">
</select>

Answer №4

Give this code a try!

var Country= {
"CA": "Canada",
"AU": "Australia",
"US": "United States",
"NZ": "New Zealand",
"UK": "United Kingdom"
}
var strInnerHTML = "";
$.each(Country, function( index, value ) {
  strInnerHTML +='<option value="'+index+'">'+value+'</option>';
});
 document.getElementById('opt_country').innerHTML = strInnerHTML;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="optCountry" id="opt_country">
</select>

Answer №5

    var countries = JSON.parse('{
    "BD": "Bangladesh",
    "BE": "Belgium",
    "BF": "Burkina Faso",
    "BG": "Bulgaria",
    "BA": "Bosnia and Herzegovina"
    }');

    //using jQuery
    countryList=[]
    $.each(countries, function(code,name) {
        countryList.push(name);
    });

     $.each(countryList, function (index, name) {
                         $("#opt_country").append($("<option></option>").val(index).html(name));
                    });

//add the following script to include jQuery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show or hide a Div based on radio button selection problem

I've successfully implemented a Div visibility toggle using the code below: $('input[name="type"]').on('change', function() { var show = $(this).val(); $(".typechoice").hide(); $("#"+show).show(); }) <script src="h ...

Importing a JSON file into a React component

I have a JSON file that I am importing in my React project: import React from 'react'; import Test1 from './test1.jsx'; import data from './data.json'; class TestWrapper extends React.Component { render () { return ( ...

Dismiss MUI Snackbar notification and execute action upon pressing a key

A custom notification system has been developed, utilizing the material ui Snackbar with both an action button and a close button. The objective is to implement a listener event for the "enter" key in order to trigger the specific notification's actio ...

Step by step guide on duplicating an AMI through CloudFormation

Can the AWS CloudFormation tool be used to replicate an Amazon Machine Image (AMI) from one region to another? ...

The effective method for transferring a PHP variable value between two PHP files using jQuery

I am looking to transmit the variable "idlaw" from base.js to the PHP page edit.php. modifyLegislation.php <input class='btn btn-primary buttonBlue' type='button' name='btnAcceptPending' value='Edit' onClick="ja ...

Moving the Promise.all feature from AngularJs to VueJs

I'm currently facing a challenge with moving a function from AngularJs to VueJs. I would really appreciate any help or suggestions you may have! items = { one: {...details here...}, two: {}, } In AngularJs: var promises = []; var deferred = $ ...

Utilize the key-value pair from ng-repeat to expand the scope of the expression

In an attempt to utilize the key value from ng-repeat as an extension of another scope.arrayResult, I aim to achieve arrayResult.q1/q2/q3 etc... <ul ng-repeat="(key,x) in data"> <li><h4>Question: {{x}}</h4> <p>{{ ar ...

How can a JSON object with duplicate property names be serialized and deserialized in a predetermined sequence?

I am faced with the challenge of creating a C# class that corresponds to this specific JSON structure, maintaining the exact bracket format: { "data": { "a": "4", "b": "2", "c": "3", "a": "444", }, } While System.Co ...

What are the steps I need to take in order to resolve the

How do I troubleshoot this issue? Error: Failed to load gRPC binary module because it was not installed for the current system Expected directory: electron-v6.0-win32-x64-unknown Found: [node-v57-win32-x64-unknown, node-v72-win32-x64-unknown] This problem ...

How can I troubleshoot jQuery not functioning in iOS even though it works on Safari?

Trying to implement jQuery on a website using xCode simulator for testing, but experiencing issues. Works fine on Safari webkit though. Click here to view the site. I would appreciate finding out what's causing the problem, as well as advice on how t ...

Troubles with retrieving native SQL Server JSON data

Trying to retrieve data from a JSON API and insert it into an SQL table in version 15.x of SQL Server has been successful when done manually. However, the process needs to be automated for archival purposes. When attempting to run it as part of a SQL Serve ...

AngularJs is being used to extract data from Firebase with the help of $value, $id, and

I have been working on retrieving data from Firebase in my HTML using AngularJS. Everything is functioning well, however, when I access the child node, the data is displayed in an unexpected format. Please refer to the images below for more details: This ...

Tips for preserving input field data in an AngularJS scope variable

I am having trouble storing textbox values in my 'Values' variable. When I enter values in the textboxes, it seems to be getting the hard-coded values instead. Can someone please help me with this AngularJS issue as I am new to it? Here is the co ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

Ways to categorize by a particular date

const vehicleDetails = [ { "record_id": "2ff8212f-5ec9-4453-b1f3-91840a3fb152", "status_date_activity": { "On Rent": 1662021991000 } }, { "record_id": "c8c1 ...

Update the message displayed in the user interface after the view has been fully rendered in an Express application, following the execution of asynchronous

I have created a simple express app that reads files from a directory, renames them, zips the files asynchronously, and then renders another view. The file reading and renaming are done synchronously, while the zipping part is handled asynchronously. My cu ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...

Obtain the value of key2 when the value of key1 is matched?

Here is a JSON object with different colors and quantities. How can you select the quantity based on the color selected by the user from a dropdown menu? { "products": [{ color: "yellow", qty: 22 }, { color: "red", ...

Unable to change placeholder in Material UI's Select Form

I'm having trouble modifying my SelectionForm. I need to update the color of the placeHolder image from red to a different color, but I can't find any properties or props on the material ui Docs to do so. Can someone assist me with this? Here is ...

Obtaining the keys of an array from a JSON input

I have an array called $json that I need to work with in PHP: $json = json_decode(' {"entries":[ {"id": "29","name":"John", "age":"36"}, {"id": "30","name":"Jack", "age":"23"} ]} '); What I am trying to achieve is to create a PHP "for each" loo ...