Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a dropdown menu from 1 to 100 using javascript

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>
like image 347
Play38 Avatar asked Nov 29 '22 08:11

Play38


2 Answers

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>
like image 126
showdev Avatar answered Dec 09 '22 18:12

showdev


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.

like image 32
Roko C. Buljan Avatar answered Dec 09 '22 19:12

Roko C. Buljan