Fill a dropdown menu from 1 to 100 using javascript

  • A+

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>


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: