Chong We Tan Chong We Tan - 7 months ago 16
Javascript Question

Populate the dropdownlist from a specfic year to current year

I'm creating a dropdownlist of year.
How can I automatically populate the dropdownlist?

For example, I will be adding a dropdown value 1980, can I use jQuery to populate it to the current year, so I will not need to type all the year?

Answer

You can use a for loop between 1980 and the current year, which you can retrieve through the getFullYear() property of a Date object. Try this:

var html = '';
for (var i = 1980; i <= new Date().getFullYear(); i++) {
    html += '<option value="' + i + '">' + i + '</option>';
}
$('#mySelect').html(html);

Working example

If you'd prefer to start with the current year and work down, you can use a negative iteration, like this:

for (var i = new Date().getFullYear(); i >= 1980; i--) {
    html += '<option value="' + i + '">' + i + '</option>';
}
Comments