0

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>
2
  • - <script> should not be child of <select> - for-loop has some different syntax than what you have tried - Search for appendChild or innerHTML than document.write Commented Nov 9, 2016 at 10:54
  • 1
    Have you done any research? There's a million websites out there that can help you with this. Commented Nov 9, 2016 at 10:54

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

2 Comments

what does i<cars.length; do just curious the script is working btw thanks, will accept in a bit
it is a lentgth of your array, to get each element , you need to loop over all elements
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.