简体   繁体   中英

How to show array list in dropdown option

after many types trying and search on google now i have no option to ask here..

my question is i want to show data in select option dropdown menu.. the date is json array list..

here is my code

<select name="" id="state_list">
     <option>select state</option>
</select>



<script>      
var url = "#";

    function getData() {
      fetch(url)
        .then((data) => {
          return data.json();
        })
        .then((covidData) => {

          var dropdown = document.getElementById("state_list");
          var stateList = covidData.data.regional;

     for (i = 0; i < stateList.lenght; i++) {
         dropdown[dropdown.lenght] = new Option(stateList[i],stateList[i]); 
    }
     })
 </script>

You could do something like below to populate your stateList to your drop-down.

var select = document.getElementById("state_list"); 
for(var i = 0; i < stateList.length; i++) {
    var opt = stateList[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}​

A working fiddle:

http://jsfiddle.net/shyntz0o/1/

You have a typo in lenght and did not close the function correctly (missing the final } ). Also your option appending logic does not work out (again because of the typo lenght ).

 window.onload = function(){ var url = "https://api.rootnet.in/covid19-in/stats/latest"; function getData(){ fetch(url).then((data) => { return data.json(); }).then((covidData) => { var dropdown = document.getElementById("state_list"); var stateList = covidData.data.regional; for(var i=0; i<stateList.length; i++){ dropdown.appendChild(new Option(stateList[i].loc, stateList[i].loc)) } }) }; getData() }
 <select name="" id="state_list"> <option>select state</option> </select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM