S SAM
S SAM

Reputation: 211

Automatically add years to HTML select using Javascript

I have a select input which will display years from this year until 1920.

However, my javascript code only seems to show it in ascending order.

  var max = new Date().getFullYear(),
    min = max - 99,
    select = document.getElementById('year');

for (var i = min; i <= max; i++) {
  var opt = document.createElement('option');
  opt.value = i;
  opt.innerHTML = i;
  select.appendChild(opt);
}
<select name="year" id="year"></select>

So it needs to show: 2019 2018 2017...

Not: 1920 1921 1922

Upvotes: 3

Views: 1172

Answers (2)

imvain2
imvain2

Reputation: 15847

There are a couple ways, use prepend, or simply count down instead of up. This method counts down. Unlike prepend, the highest is auto selected with counting down.

var max = new Date().getFullYear(),
    min = max - 99,
    select = document.getElementById('year');

for (var i = max; i >= min; i--) {
  var opt = document.createElement('option');
  opt.value = i;
  opt.innerHTML = i;
  select.appendChild(opt);
}
<select name="year" id="year"></select>

Upvotes: 4

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use ParentNode#prepend method to append at the beginning and this will make the order in descending.

var max = new Date().getFullYear(),
    min = max - 99,
    select = document.getElementById('year');

for (var i = min; i <= max; i++) {
  var opt = document.createElement('option');
  opt.value = i;
  opt.innerHTML = i;
  select.prepend(opt);
}
<select name="year" id="year"></select>

Upvotes: 2

Related Questions