Tips for displaying an array list in a dropdown menu

After trying many methods and searching on Google, I have come to a dead end and decided to ask here for help.

My question pertains to displaying data in a select option dropdown menu using JSON array list.

Below is the code snippet:

<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>

Answer №1

To populate your drop-down with the stateList values, you can use the code snippet below:

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);
}​

You can view a working example in this fiddle:

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

Answer №2

You made a mistake in spelling with "lenght" and forgot to properly close the function (missing the final "}"). Additionally, your logic for appending options is incorrect due to the misspelling of "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>

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

Encountered an issue while executing the npm run dev command in a React project

Hello, I am a beginner with React.js and I am currently trying to set up a simple React application locally using webpack. However, when I run the npm run dev command, I encounter the following error: An error occurs in the command prompt after running np ...

Why is Puppeteer failing to download to the designated folder using "Page.setDownloadBehavior" in Windows?

When trying to download a file using Puppeteer, I found that the code works perfectly on a Mac OS machine but fails on a Windows machine. The code snippet I used is shown below: await page._client.send( 'Page.setDownloadBehavior', { beha ...

Graphql query using $http.post is unsuccessful

I successfully made a request for the code below, but I am encountering an issue where I am not receiving any data back. The "preview" tab of the request in Chrome simply displays "Error Not Found". Interestingly, when I try the same query in GraphiQL, i ...

What is the process for executing a function if the Materialize.css autocomplete feature is not chosen?

Is it feasible to create a function that triggers only when a user does not select an option from Materialize.css autocomplete feature? My goal is to automatically populate an email field with a predefined value based on the user's selection in anothe ...

Adding a KMZ layer to Google Maps with Vue 2

Looking to integrate the vue google maps package? You can find it here: https://github.com/xkjyeah/vue-google-maps Within a mounted() lifecycle hook, I am attempting to set the layer as shown below: mounted() { this.$refs.gmap.$mapPromise.then((map) =& ...

Disabling a button based on the state of a switch button using React and Material UI

For the task at hand, we need to ensure that the button is only activated when the switch button's state changes. This state is received as a prop and needs to be validated correctly within the handleChangeState function. const CustomSwitch = ({name, ...

What is the best way to transfer a multidimensional array from PHP to JavaScript?

Attempting to extract array value from a JSON string, I utilize the json_decode function in PHP. <?php $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php'); $jsonDecoded=json_decode($jsonContent,true); foreach($jsonEncoded[&apo ...

What are the differences between Sitecore Analytics and Adobe Analytics? How do they each utilize JavaScript

I have limited knowledge about Sitecore Analytics (with MongoDB) and I am curious if there exists a Javascript API that can be utilized for non-Sitecore websites. If so, could you please direct me to the relevant documentation? Additionally, any insights ...

`Failure to prompt an error following an unsuccessful post request in a node.js application using axios and express`

I'm currently facing an issue while trying to implement password change validation. The problem lies in not receiving the errorMessage from the server in case of an error. Although I've successfully managed to update the password and send back a ...

Is there a way to retrieve the request object within loopback operational hooks?

I am currently utilizing loopback 3.x and have created an Access Hook within my code. My goal is to include a condition based on the User Agent. Specifically, I am looking to access Request > Headers > User-Agent. Is it feasible to retrieve this in ...

showing the names of MySQL columns stored in an array along with their corresponding data

Currently, my goal is to retrieve records from a database using MySql, store them in an array along with column headers using PDO. The reason for this is because I intend to export the data into an Excel file, and I am utilizing php-excel for this purpose. ...

Unusual marker appearing on every page utilizing ionic v1 and angularjs

For some unknown reason, a dot appears at the upper left side of each page in my webapp: https://i.stack.imgur.com/nN61t.png It seems to be an issue with the HTML code. When I run the snippet below, the dot is visible: <ion-view view-title="Send fe ...

Utilizing Javascript to load a vast amount of data onto the browser, followed by initiating an XML

Looking for a solution to send XML requests containing values and content from files obtained by filling out an HTML form. With 5 large files, some exceeding 70 MB, I have implemented JavaScript functions to load file contents and assemble the XML request. ...

Extending fabric.js toObject with custom properties can result in the loss of default properties

After doing extensive research on various platforms, including this one, I am still struggling to get everything working as desired. My main goal is to save custom properties in all shapes, specifically the uuid and rt_attributes. Following the manual, I ...

Using a pipe filter to implement a search feature in an Ionic search bar

Hey everyone, I'm facing a little issue here. I created a pipe filter to sort through some data, but now I need to include two more filters and I'm not sure how to go about it within this pipe. Below is an example of the pipe I have created: ...

Mongoose JS is unable to display the query value in the output

Is there a way to use mongoose js to create a collection of kittens with specific attributes like {name: "mike"}? Once this document is created, I need to be able to view its value. I've attempted to write the following code: However, I've enco ...

What is the purpose of using href="javascript:void()?

As I was pondering over this query: What exactly does "javascript:void(0)" signify?, I realized the rationale behind using <a href="javascript:void(0)" - to prevent any redirection of the page. Recently, I stumbled upon this snippet of code: <a id= ...

Expanding size on hover without affecting the alignment of surrounding elements

Imagine there are 10 divs on the page styled as squares, collectively known as the home page. Among these 10: 3 divs belong to the .event1 class, 5 divs belong to the .event2 class, and 2 divs belong to the .event3 class. <div class="boxes event1"> ...

Layered parallax scenery

I'm interested in creating a parallax effect similar to this example. https://medium.com/@PatrykZabielski/how-to-make-multi-layered-parallax-illustration-with-css-javascript-2b56883c3f27 However, I find the use of HAML and Coffeescript in the mentio ...

Exploring the possibilities of developing WebComponents within Angular using TypeScript

My Angular application was originally created using the default method with ng new project-name". However, for performance reasons, I had to incorporate single standard WebComponents. The JavaScript code associated with these components is stored in a ...