Sanjeev Sanjeev - 7 months ago 26
Javascript Question

I want fill five years in a drop-down using javascript and the years will be after the current years

I want fill five years in a drop-down using javascript and the years will be after the current year.

for example:

if current year is 2012 then the drop-down values are 2012,2013,2014,2015,2016

Answer

HTML

<form id="someform">
<select id="year"></select>
</form>

JavaScript

var myselect = document.getElementById("year"), year = new Date().getFullYear();
var gen = function(max){do{myselect.add(new Option(year++,max--),null);}while(max>0);}(5);

A little bit better JavaScript function:

var myselect = document.getElementById("year"),
    startYear = new Date().getFullYear()
    count = 5;

(function(select, val, count) {
  do {
    select.add(new Option(val++, count--), null);
  } while (count);
})(myselect, startYear, count);

jsFiddle, new jsFiddle

Comments