4

I'm trying to populate a drop down menu with a javascript array. I can get individual elements to show up but not the entire array. I'm sure this question has been asked before, but can't find any references. Any help would be appreciated.

var sex=["male","female", "unknown"];

for (i=0;i<sex.length;i++){
var opt = document.createElement("option");
document.getElementById("m").innerHTML=sex[i];
}

The html is:

    <form name = "demo">
    <table id = "demo">
    <th>Demographics</th>
    <tr><td>Sex</td><td><select><option id="m"></option></select></td></tr>
    </table>
    </form>
David
  • 43
  • 1
  • 1
  • 5

3 Answers3

2

See below an non-elegant fix to your problem. You can refactor this to nicer looking code if you use the JQuery library, see for example What is the best way to add options to a select from an array with jQuery?

var sex = ["male", "female", "unknown"];

for (i = 0; i < sex.length; i++) {
  var opt = document.createElement("option");
  document.getElementById("m").innerHTML += '<option id="' + i + '">' + sex[i] + '</option>';
}
<form name="demo">
  <table id="demo">
    <th>Demographics</th>
    <tr>
      <td>Sex</td>
      <td>
        <select id="m">

        </select>
      </td>
    </tr>
  </table>
</form>
Community
  • 1
  • 1
Alex
  • 21,273
  • 10
  • 61
  • 73
1

This is a method I typically use that works:

Codepen Demo

HTML:

<form name="demo">
  <table id="demo">
    <th>Demographics</th>
    <tr>
      <td>Sex</td>
      <td>
        <select id = "sex">

        </select>
      </td>
    </tr>
  </table>
</form>

Javascript:

//array to hold the persons sex
var sex = ["male", "female", "unknown"];

//array to store html to add to the select list
var html = [];

//loop through the array
for (var i = 0; i < sex.length; i++) {//begin for loop

  //add the option elements to the html array
  html.push("<option>" + sex[i] + "</option>")

}//end for loop

//add the option values to the select list with an id of sex
document.getElementById("sex").innerHTML = html.join("");
Larry Lane
  • 2,141
  • 1
  • 12
  • 18
  • Try this again (didn't go through the first time)... this is perfect. Thank you all for your suggestions. – David Oct 03 '15 at 20:16
-1

Use a template libary like underscore or handlebars or mustache. Its bad practice to generate html from javascript.

Bhushankumar Lilapara
  • 780
  • 1
  • 13
  • 26
  • Can you elaborate why you believe it is bad practive to generate html from JavaScript. Does underscore,handlebars, and mustache use JavaScript? – Larry Lane Oct 03 '15 at 19:41
  • You can Google it, you will get lot's answers for it. http://stackoverflow.com/questions/1284381/why-is-it-a-bad-practice-to-return-generated-html-instead-of-json-or-is-it – Bhushankumar Lilapara Oct 03 '15 at 19:44