Code snippet: Bind the select elements for the month numbers and years in JavaScript

In the following code snippets you’ll see that how to bind the month numbers 1 to 12 and year range into the select elements at run time using JavaScript.

Bind the Month numbers 1 to 12

This JavaScript function will add the month numbers in the select element named ‘ddlMonth’.

 function addMonthList() {  
    var select = document.getElementById("ddlMonth");
    var max = 12;
    for (var i = max; i >= 1; --i) {
        var option = document.createElement('option');
        option.text = option.value = i;
        select.add(option, 0);
    }
  }

Bind the years
The function binds the years in the select element at runtime using JavaScript.

function addListyear() {
    var select = document.getElementById("ddlExpyear");
    for (var i = 2033; i >= 2013; --i) {
        var option = document.createElement('option');
        option.text = option.value = i;
        select.add(option, 0);
    }
}

The following is the html code in which both select elements are located:
HTML Code

<div class="divfield">
    Select Month:
    <select id="ddlMonth" class="selectcontrol"></select>
</div>
<div class="divfield">
    Select Year:
    <select id="ddlExpyear" class="selectcontrol"></select>
</div>