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.

6
  • 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. Commented Feb 26, 2016 at 11:25
  • In that case check browser console for errors. Commented Feb 26, 2016 at 11:26
  • Did you correctly loaded the js file into HTML ? Commented Feb 26, 2016 at 11:28
  • Yes I correctly linked the external javascript file, I tested that. Commented Feb 26, 2016 at 11:32
  • Script should be added in document.ready event or after <select id="CuisineList"></select> Commented Feb 26, 2016 at 12:00

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.