使用JavaScript显示最近3个月的下拉列表 [英] Display dropdown of last 3 months using javascript

查看:78
本文介绍了使用JavaScript显示最近3个月的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下拉列表中的javascript显示本月的最后3个月(包括总计4个月)

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;
            }
        }
    }
}

简单地说,在视图部分中显示当月和前3个月的下拉列表. 后端,则需要以[YYYYMM]的身份提交.

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].

如果bean中已经存在值,则在下拉列表中将其显示为选定值. [保证会在这4个月内]

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

推荐答案

此函数返回最近几个月的n,包括当前月份:

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;

}

致电:

document.write(getLastMonths(4));

打印:

201211,201210,201209,201208

演示

然后,在下拉框中添加这些值非常简单:

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);
    }

}

只需使用:

writeMonthOptions();

完整示例

这篇关于使用JavaScript显示最近3个月的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆