Copy link to clipboard
Copied
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>
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.
Copy link to clipboard
Copied
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.
Copy link to clipboard
Copied
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
}
Copy link to clipboard
Copied
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.
Copy link to clipboard
Copied
So sorry for the delay getting back...
Thanks so much try67 - sinious and Liam - That info is super helpful - works great!
Thanks Again - Dave
Get ready! An upgraded Adobe Community experience is coming in January.
Learn more