Display dropdown of last 3 months using javascript

2019-03-04 00:07发布

问题:

I am trying to display last 3 months of present month (including this total four months) using javascript in drop down

function writeMonthOptions() {
    var months = new Array("01", "02", "03", "04", "05", "06", "07", "08",
            "09", "10", "11", "12");
    var today = new Date();
    var date = new Date(today);
    date.setFullYear(date.getFullYear() - 1);
    var dropDown = document.getElementById("Month_list");
    var i = today.getMonth();
    var optionNames;
    var optionValues;
    var beanData = '<s:property value="month" />';
    while (i < (today.getMonth() + 4)) {
        optionNames = months[i];
        optionValues = today.getFullYear() + '' + months[i];
        dropDown.options[i++] = new Option(optionNames, optionValues);
        if (beanData) {
            if (beanData == (today.getFullYear() + "" + monthsInd[today
                    .getMonth()])) {
                dropDown.selectedIndex = i - 1;
            }
        }
    }
}

in simple, show drop down of present month and previous 3 months in the view part. to back-end it needs to be submitted as [YYYYMM].

if already value present in bean, show it as selected in drop down. [guaranteed that it will be in those 4 months]

回答1:

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