using javascript to loop through drop down html array
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>
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>
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("");
Use a template libary like underscore or handlebars or mustache. Its bad practice to generate html from javascript.
链接地址: http://www.djcxy.com/p/47904.html