Search code examples
javascriptnode.jsjsonajaxdropdown

display json object in dropdown


I am hoping to get some help from the community. I am trying to understand how to write a code to read from a json file to a dropdown . I am using node.js to run the app.

I am accessing json object from "http://localhost:4300/location": { "1": "82 North Wall Quay, Dublin 1", "2": "Eastwall Wall Road, Dublin 3", "3": "4 Grand Canal Square,Dublin 2 " }

<select id="location"> </select>

function populateSelect(shop_location){

var xhttp = new XMLHttpRequest
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status==200) {

showResult(xhttp.responseText);
}
};
xhttp.open("GET", "http://localhost:4300/location", true);
xhttp.send();
}

function showResult(jsonData) {
var txt = "";
var jsonData = JSON.parse(jsonData);
jsonData.forEach (x=>{txt = txt + "<br>" +x["Title"];})

document.getElementById("location").innerHTML = txt;
}

Thanks


Solution

  • You can use a for..in loop to iterate through all the keys of the JSON object and create a new option element for each of them.

    Finally use the append() method to add each newly created option element to the select element.

    Check below:

    var jsonData = { 
      "1": "82 North Wall Quay, Dublin 1",
      "2": "Eastwall Wall Road, Dublin 3",
      "3": "4 Grand Canal Square,Dublin 2"
    };
    
    function showResult(jsonData) {
      let loc = document.getElementById("location");
      
      for(let key in jsonData) {
        let option = document.createElement("option");
        option.innerHTML = jsonData[key];
        option.value = key;
        loc.append(option);
      }
    }
    
    showResult(jsonData);
    <select id="location">
    </select>