0

Newbie JS here, I need to populate a dropdown list from an array of 10 cities and I just cannot get any code to work.

<select id="selectCity">
<option>Choose a City</option>
</select>

var select = document.getElementById('selectCity');
var options = ["Winthrop","Revere","Malden","East Boston","Medford","Somerville","South Boston","Quincy","Malden","Weymouth"];

//what code will work in this loop below???

for(var i = 0; i < options.length; i++) { 

}
winseybash
  • 704
  • 2
  • 12
  • 27

3 Answers3

2

Try this code.

var select = document.getElementById('selectCity');
var options = ["Winthrop","Revere","Malden","East Boston","Medford","Somerville","South Boston","Quincy","Malden","Weymouth"];

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}​
Rohit Chopra
  • 477
  • 1
  • 4
  • 11
2

try this

var select = document.getElementById('selectCity');
var options = ["Winthrop", "Revere", "Malden", "East Boston", "Medford", "Somerville", "South Boston", "Quincy", "Malden", "Weymouth"];

//what code will work in this loop below???

var s = document.getElementById("selectCity");
for (var i = 0; i < options.length; i++) {
  s.innerHTML += `<option value=${i}> ${options[i]}</option>`;
}
<select id="selectCity">
  <option>Choose a City</option>
</select>
RizkiDPrast
  • 1,695
  • 1
  • 14
  • 21
1

It'll works for you!

You just need to put this code in your loop:

var option = document.createElement("option");

option.text = options[i];

option.value = options[i];

select.appendChild(option);

<select id="selectCity">
    <option>Choose a City</option>
</select>

<script type="text/javascript">
    var select = document.getElementById('selectCity');
    var options = ["Winthrop","Revere","Malden","East Boston","Medford","Somerville","South Boston","Quincy","Malden","Weymouth"];
    for(var i = 0; i < options.length; i++) {
        var option = document.createElement("option");
        option.text = options[i];
        option.value = options[i];
        select.appendChild(option);
    }
</script>
Andrew Savetchuk
  • 1,552
  • 1
  • 16
  • 21