rickyProgrammer
rickyProgrammer

Reputation: 1167

Get the years before the current year in dropdown using Javascript

I have a working code which loads the 10 years after of the current year in the dropdown, havig the current year as the selected item. What I need to add is the 10 years BEFORE the selected or current year.

Here's the code

<select id="year" class="" style="width: 100%; display:inline-block;" value="" ></select>

<script>
    var currentYear = new Date().getFullYear()
    max = currentYear + 10
    var options = "";
    for (var year = currentYear ; year <= max; year++) {
        options += "<option>" + year + "</option>";
    }
    document.getElementById("year").innerHTML = options;
</script>

Upvotes: 0

Views: 3147

Answers (1)

Dinesh undefined
Dinesh undefined

Reputation: 5546

Create option using createElement and append it to select.

var currentYear = new Date().getFullYear()
    max = currentYear + 10
    var option = "";
    for (var year = currentYear-10 ; year <= max; year++) {
      
        var option = document.createElement("option");
        option.text = year;
        option.value = year;
        
        document.getElementById("year").appendChild(option)
        
    }
    document.getElementById("year").value = currentYear;
<select id="year" class="" style="width: 100%; display:inline-block;" value="" ></select>

Upvotes: 3

Related Questions