I've tried to write a javascript code which fills the select tags with option tags from 1 to 100.
But instead of giving me 99 options, it gives me only one option with the 100 value on it.
I would be happy to understand and to know how to solve this problem.
var selectAge = document.getElementById("selectAge");
document.onload = (function(){
for(let i = 1; i<=100 ; i++)
selectAge.innerHTML ="<option>" + i + "</option>";
})();
<form>
<label>
Your age:
<select name="age" id="selectAge"></select>
</label>
</form>
You are overwriting the innerHTML
upon each iteration of the loop.
One solution is to concatenate with the addition assignment operator: +=
.
var selectAge = document.getElementById("selectAge");
for (let i = 1; i <= 100; i++)
selectAge.innerHTML += "<option>" + i + "</option>";
<select name="age" id="selectAge"></select>
As mentioned by Ivan, to avoid rewriting the innerHTML
100 times, I suggest building a string first:
var selectAge = document.getElementById("selectAge");
var contents;
for (let i = 1; i <= 100; i++) {
contents += "<option>" + i + "</option>";
}
selectAge.innerHTML = contents;
<select name="age" id="selectAge"></select>
Beside (as already noted by others) you're using =
instead of +=
to concatenate, it's a bad idea to manipulate 100 times the DOM,
instead, use innerHTML
only once:
let ageOptions = "";
for(let i=1; i<=100 ; i++) ageOptions += `<option>${i}</option>`;
document.querySelector("[name=age]").innerHTML = ageOptions;
Your age: <select name="age"></select>
Also, to make sure DOM is parsed ready to be manipulated, (instead of window.onload
and similar) simply place your <script>
tag right before the closing </body>
tag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With