Ricardo Andres Ricardo Andres - 1 month ago 7
Javascript Question

Removing past and current month options from selectbox based on year selected

I am creating a form that includes two select boxes to allow users to choose a month and year to cancel a membership. The month selected should not be the current month nor past months. I added some jQuery to pre-select the month after the current one, but it still allows users to select a previous month if they want.

What I would like to implement is a script that removes options based on the year selected. For example: If 2016 is selected (and we're in October 2016 now), the script should remove options 1 through 10.

I suspect it is not too complicated, but my knowledge of jQuery is very limited. Thanks in advance.

Codepen: http://codepen.io/ricardoh/pen/vXpdvQ

Here is the HTML:

<select id="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>

<select id="year">
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
</select>


And the jQuery:

$(function(){
var month = new Date().getMonth() + 1;
if( month > 12 ) month = 1;
document.getElementById("month").options[month].selected = true;
});

Answer

How about something like this? JSFiddle

function adjustMonths() {
   var thisYear = new Date().getFullYear() + ""; //Get current year
   var nextMonth = new Date().getMonth()+2 + ""; //Get next month
   var selectedYear = $('#year option:selected').val(); //Selected Year
   if (nextMonth .length == 1) {
      nextMonth = "0" + nextMonth ; //Add preceding "0" to single-digit month
   }

   var yearAndMonth = parseInt(thisYear+nextMonth); //Create integer of year+month

   $('#month option').each(function() { //Loop through all month options

      var selectMonth = $(this).prop('value'); //Get option value

      if (selectMonth.length == 1) {
         selectMonth = "0" + selectMonth; //Add preceding "0" to single-digit month
      }

      if (parseInt(selectedYear + selectMonth) < yearAndMonth) {
         $(this).hide(); //If the selected year + this month are less than the current year and month, hide this month
      } else {
         $(this).show(); //Otherwise, show it
      }

   });

   $("#month option").prop('selected', false); //Unselect all
   $("#month").find("option:visible:first").prop('selected', true); //Select first visible month from dropdown

}

$(document).ready(function() {
    adjustMonths(); //run script on pageload

    $('#year').change(function() {
      adjustMonths(); //run script when changing the year dropdown
    })

});
Comments