Innate Innate - 6 months ago 12
Javascript Question

create a dropdown list in javascript using months from this month

I have a "search by month" feature and have listed the months in a dropdown (select) field. I wish to only display months from this month onward (including this month) for 5 years ahead. This is what I have so far:

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;


Im adding this HTML to my page with JavaScript and then loading the results based on the month and year with values in the select options like this: 01-2015, 02-2015, 03-2015, etc. where January is 01 (and not 0)

Answer

See my demo here. It displays September onwards for this year, and all months for subsequent years.

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