Reputation: 4286
I have an array, i want each value inside the array to be displayed in a input select box as an option. This is what i have tried myself:
<select>
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
for(cars)
{
document.write("<option>"cars"</option>");
}
</script>
</select>
Upvotes: 0
Views: 56
Reputation: 2642
You can use the below code and try:
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var select_c = '<select>';
for(var i=0;i<cars.length;i++)
{
select_c += '<option>'+cars[i]+'</option>';
}
select_c += '</select>';
document.write(select_c);
</script>
You can see the fiddle here: Demo
Upvotes: 0
Reputation: 4987
with this javascript it should be like this
<select id="MySelectBox">
</select>
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
for (i=0; i<cars.length; i++) {
option+= "<option value='"+cars[i]+"'>"+cars[i]+"</option>";
}
document.getElementById("MySelectBox").html= option;
</script>
Upvotes: 2
Reputation: 7013
you can make it with for loop easily
<script language="javascript" type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
for(var i=0;i<cars.length;i++)
{
var diVContent = '<option>'+cars[i]+'</option>';
document.write(diVContent);
}
</script>
Upvotes: 1