使用本月的月份在javascript中创建一个下拉列表

时间:2015-09-07 11:30:50

标签: javascript html-select

我有一个“按月搜索”功能,并在下拉列表(选择)字段中列出了月份。我希望只显示本月(包括本月)的月份,为期5年。这就是我到目前为止所做的:

var multiYears = [ "2015", "2016", "2017", "2018", "2019", "2020"];
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var htmlOptions = "";
var i;
for (m = 0; m < multiYears.length; m++) {
  var multiYear = multiYears[m];
  for (i = 0; i < 12; i++) {
      var realMonth = i + 1;          
      htmlOptions += '<option value="' + ("0" + realMonth).slice(-2) + "-" + multiYear + '">' + monthNames[i] + " " + multiYear + '</option>';
  }
}

var htmlStart = '<select size="1" id="multiDrop" name="multiDrop">';
var htmlOptionsHeader = '<option value="_">Navigate by month</option>';
var htmlEnd ='</select>';
var html = htmlStart + htmlOptionsHeader + htmlOptions + htmlEnd;

我使用JavaScript将此HTML添加到我的页面,然后根据月份和年份将结果加载到选择选项中的值,如下所示:01-2015,02-2015,03-2015等,其中January为01 (而不是0)

1 个答案:

答案 0 :(得分:0)

查看我的演示here。它显示了今年9月以及随后几年的所有月份。

var multiYears = [ "2015", "2016", "2017", "2018", "2019", "2020"];
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var htmlOptions = "";
var i;


var currentDate = new Date();

for (m = 0; m < multiYears.length; m++) {
  var multiYear = multiYears[m];
  var startMonth = 1;
  // if it's the current year, only show from this month onwards
  if (multiYear == currentDate.getYear() + 1900) {
      startMonth = currentDate.getMonth() + 1;
  }

  for (i = startMonth ; i <= 12; i++) {
      htmlOptions += '<option value="' + ("0" + i).slice(-2) + "-" + multiYear + '">' + monthNames[i - 1] + " " + multiYear + '</option>';
  }
}

var htmlStart = '<select size="1" id="multiDrop" name="multiDrop">';
var htmlOptionsHeader = '<option value="_">Navigate by month</option>';
var htmlEnd ='</select>';
var html = htmlStart + htmlOptionsHeader + htmlOptions + htmlEnd;

document.body.innerHTML += html;