Home > Enterprise >  Display a <select> with information from an API in?
Display a <select> with information from an API in?

Time:10-15

I'm trying to figure out how to display information from an API in a select.

The user has to select a start station with the itself linked to the api. But I can't create option, having the names of each station, in my select.

Can you help me understand my mistake?

<section class="container">
  <div class="item">
  <p>list</p>
  <select id="subwaystation"> 
  </select>

var apiStations = "https://api-ratp.pierre-grimaud.fr/v4/stations/metros/8";

function req1() {
fetch(apiStations, {
  method: "get"
})
  .then(response => response.json())
  .then(data => {
   let allstations= data.result.stations;
    for(var i = 0; i < allstations.length; i  ) {
      html  = "<option value="   key    ">"  obj[key]   "</option>"
  }
  document.getElementById("subwaystation").innerHTML = html;
  })
}
req1();

CodePudding user response:

Your code contains some simple errors which you should be able to see in your browser's Console, which would give you clues about why it's not working.

First you'd see that html is not defined before you try to append to it. You can't append to something which doesn't exist.

if you fix that then you'd see that key and then obj are also not defined. It's not clear where you expected those to come from or what you think they would contain. I wonder if you simply copied and pasted some code you found without stopping to examine it properly or consider whether it fits with the context you pasted it into.

You can fix these issues very straightforwardly by

  1. declaring html as an empty string before your loop starts, so the = has something to append to
  1. When creating the <option, referring to the station object at the current index (i) of the loop and then the specific properties found in that object (slug and name, as shown in the raw JSON), instead of using key and obj which do not come from anywhere else in your code.

Demo:

var apiStations = "https://api-ratp.pierre-grimaud.fr/v4/stations/metros/8";

function req1() {
  fetch(apiStations, {
      method: "get"
    })
    .then(response => response.json())
    .then(data => {
      let allstations = data.result.stations;
      let html = '';
      for (var i = 0; i < allstations.length; i  ) {
        html  = "<option value="   allstations[i].slug   ">"   allstations[i].name   "</option>"
      }
      document.getElementById("subwaystation").innerHTML = html;
    })
}
req1();
<select id="subwaystation">
</select>

  • Related