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
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
You could get the list of years like so...
var date = new Date,
years = [],
year = date.getFullYear();
for (var i = year; i < year + 5; i++) {
years.push(i);
}
jsFiddle.
Or to actually create your select
element...
var date = new Date,
year = date.getFullYear(),
select = document.createElement('select');
for (var i = year; i < year + 5; i++) {
var option = document.createElement('option'),
yearText = document.createTextNode(i);
option.appendChild(yearText);
select.add(option);
}
select.name = 'year';
document.body.appendChild(select);
jsFiddle.
If you use jQuery, the task can be achieved as follow:
var currentYear = new Date().getFullYear();
for (var i = 1; i <= 5; i++ ) {
$("#timeSelector").append(
$("<option></option>")
.attr("value", currentYear)
.text(currentYear)
);
currentYear++;
}
View demo at jsFiddle
var currentYear = new Date().getFullYear();
for (var i = 0; i < 5; i++ ) {
$("#years").append(
$('<option/>')
.attr("value", currentYear + i)
.text(currentYear + i));
}
精彩评论