mercredi 6 mai 2020

Array object not displaying in id="main" in a for loop using onchange function

I have also tried using the document.write function. It works, but it will remove the other contents of the page in the ID that I am trying to display it on. Is there a way I can display this for loop inside the ID that I am targeting? It only displays "Normal,Il" and that is about it. Can someone help me? Thank you.

var cities = [
  { city: "Bloomington, IL",
    latitude: "40.4842° N, 88.9937° W",
    population: "77,962",
    elevation: "797 feet (243 m) above sea level",
  },
   { city: "Normal, IL",
     latitude: "40.5142° N, 88.9906° W",
     population: "54,742",
     elevation: "869 feet (265 m) above sea level",
   }
];


function displayCityInfo() {
  var x = document.getElementById("cityInfo").value;
  document.getElementById('main').innerHTML = "<br>You selected: " + x;

  for(i=0; i<cities.length; i++){
    document.getElementById('main').innerHTML = (cities[i].city + "<p></p>");
  }
}

  <body>
    <h1>City Information</h1>
      <label>Select an option:</label>
      <select id="cityInfo" onchange="displayCityInfo()">
        <option selected disabled>Select an option</option>
        <option value="1" enabled>Latitude/Longitude</option>
        <option value="2" enabled>Population</option>
        <option value="3" enabled>Elevation</option>
      </select>
    <main id ="main">
    </main>
  </body>





Aucun commentaire:

Enregistrer un commentaire