Fill a html select by means of a javascript cycle

1

I want to fill a select dynamically with years, starting from the year 2000 to 2050, through a for javascript. But the code still does not work for me.

HTML

<select id="año">
</select>

JAVASCRIPT

select = document.getElementById("año");
option = document.createElement("option");
for(i = 2000; i <= 2050; i++){
  option.value = i;
  option.text = i;
}
select.appendChild(option);

And at the end I only create a single option with the value of 2050.

    
asked by David Espinal 02.08.2018 в 23:33
source

2 answers

4

Try the following code:

select = document.getElementById("año");
for(i = 2000; i <= 2050; i++){
    option = document.createElement("option");
    option.value = i;
    option.text = i;
    select.appendChild(option);
}
<select id="año"> </select>

For each iteration in the cycle for you must create an element option and in the same way add it to the element select .

    
answered by 02.08.2018 / 23:37
source
0

This is the friend solution:

select = document.getElementById("año");
for(i = 2000; i <= 2050; i++){
  option = document.createElement("option");
  option.value = i;
  option.text = i;
  select.appendChild(option);
}
<select id="año">
</select>
    
answered by 02.08.2018 в 23:40