Reputation: 61
I am trying to populate html select with javascript array, can you guys help me make this one work below are my codes
external javascript (I have found this code somewhere in the internet)
function setRuleName()
{ var myCars=new Array("Saab","Volvo","BMW");
var sel = document.getElementById("dropping") // find the drop down
for (var i in myCars)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = title[i]; // set the value
opt.text = title[i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
html code
<Select onclick="setRuleName();" id="dropping" >
</Select>
Upvotes: 1
Views: 135
Reputation: 16716
Alternative ways to write this code.
function setRuleName(){
var myCars=["Saab","Volvo","BMW"],
sel=document.getElementById("dropping");
for(var a=0,tit;tit=myCars[a];++a){
var opt=document.createElement("option");
opt.value=opt.textContent=tit;
sel.appendChild(opt);
}
}
For internal use (NO POST)
function setRuleName(){
document.getElementById("dropping").innerHTML='<option>'+
["Saab","Volvo","BMW"].join('</option><option>')+
'</option>';
}
to access the value :
console.log(document.getElementById("dropping").selected.textContent);
Upvotes: 1
Reputation: 104805
Not sure where your title
attribute came from, but when looping an array, use a standard for
, not a for in
for (var i = 0; i < myCars.length; i++) {
var opt = document.createElement("option"); // Create the new element
opt.value = myCars[i]; // set the value
opt.text = myCars[i]; // set the text
sel.appendChild(opt); // add it to the select
}
Upvotes: 2