0

I just want to fill select with array values.

Here is js code (which I took from here). It doesn't work even without loop. So if I could make it work, then filling with array won`t be a problem.

var sel = document.getElementById('CountrySelect');     
var opt = document.createElement('option');
opt.innerHTML = "CountyNumerOne";
opt.value = 0;
sel.appendChild(opt);
<select id="CountrySelect">
</select>

But on the output I get empty list

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 2
    As you can see from having changed your exact code to be a [mcve] the code works just fine, so there is some difference between what you have here and what's going on in your real project. My guess is you're running the javascript before the `select` element is on the page. – Jamiec Jul 01 '20 at 12:02
  • @Jamiec oh, Im such a noob. Ive moved script to the end and now its working. Thank you! – Keshker Jul 01 '20 at 12:06
  • Ha, don't be hard on yourself. We've all made a similar mistake. – Jamiec Jul 01 '20 at 12:10

2 Answers2

2

You must ensure the script is triggered after the select element is parsed by the browser. You can do this either by putting the script tag after your select element, or listening for the document loaded event in your script:

<script>
    document.addEventListener("DOMContentLoaded", function(event) { 
        var sel = document.getElementById('CountrySelect');
    
        var opt = document.createElement('option');
        opt.innerHTML = "CountyNumerOne";
        opt.value = 0;
        sel.appendChild(opt);
    });
</script>
Aiden Foxx
  • 29
  • 2
0
var select = document.getElementById("CountrySelect"); 
var options = ["1", "2", "3", "4", "5"]; //array
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);
}​

http://jsfiddle.net/yYW89/