I am trying to display last 3 months of present month (including this total four months) using javascript in drop down
function writeMonthOptions() {
var mon
This function returns the n
last months, including the current one:
function getLastMonths(n) {
var months = new Array();
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var i = 0;
do {
months.push(year + (month > 9 ? "" : "0") + month);
if(month == 1) {
month = 12;
year--;
} else {
month--;
}
i++;
} while(i < n);
return months;
}
Call:
document.write(getLastMonths(4));
Prints:
201211,201210,201209,201208
Demo
Then, adding those values within a dropdown box is quite easy:
function writeMonthOptions() {
var optionValues = getLastMonths(4);
var dropDown = document.getElementById("monthList");
for(var i=0; i<optionValues.length; i++) {
var key = optionValues[i].slice(4,6);
var value = optionValues[i];
dropDown.options[i] = new Option(value, key);
}
}
Just use:
writeMonthOptions();
Full example