2

I have found several links to populate a dropdown list with an array but none of them work for me. Some links I have tried include:

This similar Stack Overflow question: JavaScript - populate drop down list with array

This similar situation:

Javascript:

var cuisines = ["Chinese","Indian"];     

var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = cuisines[i];
opt.value = cuisines[i];
sel.appendChild(opt);
}

and the HTML:

<select id="CuisineList"></select>

But nothing is working. My goal is to populate a dropdown list from an external javascript array with values 0 to 255 so they can be used to come up with an RGB scheme. This is similar to the question that has been linked, but the linked question does not work when I copy and paste it into my text editor and preview it in Chrome.

Community
  • 1
  • 1
  • Hey thanks for the reply. Did you just try it out in the editor on the website? That works for me but when I copy and paste it into my text editor and then preview it, it doesn't work. –  Feb 26 '16 at 11:25
  • In that case check browser console for errors. – Pardeep Dhingra Feb 26 '16 at 11:26
  • Did you correctly loaded the `js` file into HTML ? – Munawir Feb 26 '16 at 11:28
  • Yes I correctly linked the external javascript file, I tested that. –  Feb 26 '16 at 11:32
  • Script should be added in document.ready event or after `` – Gene R Feb 26 '16 at 12:00
  • Did you put this code inside this window.onload = function(){ ... } Just to ensure that the code is correctly executed after the page is completely loaded – Ema.jar Feb 26 '16 at 12:02

2 Answers2

1

try this:

i think your dom not ready when script executed

function ready() {
     var cuisines = ["Chinese","Indian"];     

     var sel = document.getElementById('CuisineList');
     for(var i = 0; i < cuisines.length; i++) {
      var opt = document.createElement('option');
      opt.innerHTML = cuisines[i];
      opt.value = cuisines[i];
      sel.appendChild(opt);
    }
  }

  document.addEventListener("DOMContentLoaded", ready);
<select id="CuisineList"></select>
0

try this

var cuisines = ["Chinese","Indian"];
var innerData = '';
for(var i = 0; i < cuisines.length; i++) {
    innerData += '<option value="' + 'cuisines[i]' + '">' + 'cuisines[i]' + '</option>';
}
document.getElementById('CuisineList').innerHTML = innerData;
Jishnu KM
  • 234
  • 1
  • 8