Display dropdown of last 3 months using javascript

前端 未结 1 1543
温柔的废话
温柔的废话 2021-01-26 02:45

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         


        
相关标签:
1条回答
  • 2021-01-26 03:41

    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

    0 讨论(0)
提交回复
热议问题