Skip to main content
Inspiring
June 28, 2019
Answered

Need help with JavaScript form select options

  • June 28, 2019
  • 4 replies
  • 903 views

Hi all,

I'm trying to create a simple form selection using a JavaScript loop and it is not displaying on the page. The span tag by itself will display the items however when I put it inside of the select tag it does not display. I'm not sure exactly what's wrong and could use any assistance.

Thanks Dave

<form>

<select>

<span id="demo5"></span>

<option value="123">123</option>

<option value="456">456</option>

</select>

</form>

<script>

var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

var text = "";

var i;

for (i = 0; i < cars.length; i++) {

text += "<option value=\"" + cars + "\">" +  cars + "</option>";

}

document.getElementById("demo5").innerHTML = text;

</script>

This topic has been closed for replies.
Correct answer try67

Remove the span tag and set the id property of the select tag, instead.

Of course, the code will overwrite the default values you added to it, so either move them to your code or have the code copy them and add the new items to them, before applying them back.

4 replies

revdaveAuthor
Inspiring
August 7, 2019

So sorry for the delay getting back...

Thanks so much try67 - sinious and Liam - That info is super helpful - works great!

Thanks Again - Dave

Liam Dilley
Inspiring
August 7, 2019

If you looked to use jQuery you can more easily do this with correct markup because a span inside the select is not great syntax.

I created an example here:
https://jsfiddle.net/c3g82q7r/

A bit late but forum maintenance and then being busy stopped me posting.

sinious
Legend
July 2, 2019

The <select> </select> expects <option> </option> values inside it which is why it is behaving oddly. Doing as mentioned above corrects that problem.

Optionally you can use vanilla JS to insert the items, e.g.:

var sel = document.getElementById('demo5');

...

for (i = 0; i < cars.length; i++) {

    var opt = document.createElement("option");

    opt.text = cars;

    opt.value = cars;

    sel.add( opt, sel.options ); // add option at index i

}

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
June 29, 2019

Remove the span tag and set the id property of the select tag, instead.

Of course, the code will overwrite the default values you added to it, so either move them to your code or have the code copy them and add the new items to them, before applying them back.