Listing of months with year december getting wrong year

$("select").change(function() {
  //var date = "2017-04-06"
  //var date = "2017-01-06"
  $(".appendhere").empty();
  var date = $("option:selected",this).text();
  var monthnumber = date.split("-")[1] - 1;
  var yearnumber = date.split("-")[0];
  var months = 12;
  var m_names = new Array("January", "February", "March",
    "April", "May", "June", "July", "August", "September",
    "October", "November", "December");
  for (var i = months - 1; i >= 0; i--) {
    var div = $('<div class="row" style="margin-top:6px;"><div class="col-md-6"><label class="col-md-6 col-form-label">' + yearnumber + " " + m_names[monthnumber] + '</label></div>');
    $(".appendhere").append(div)
    monthnumber == 11 ? monthnumber = 0 : monthnumber++;
    m_names[monthnumber] == "December" ? yearnumber++ : yearnumber + 0;
  }

}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>

<option>2017-04-06</option>
<option>2017-01-06</option>
</select>

<div class="appendhere"></div>

On change of select I want to append months with year based on the date of select.

I can add the month and year but the problem is the year for December is always 1 year ahead of the year.

I know it is small details but I cant point out where i did wrong.

Answers 1

  • Hope this will work.

         for (var i = months -1; i >= 0; i--) {
             monthnumber == 11 ? monthnumber = 0 : monthnumber++;
             var div = $('<div class="row" style="margin-top:6px;"><div class="col-md-6"><label class="col-md-6 col-form-label">' + yearnumber + " " + m_names[monthnumber] + '</label></div>');
             $(".appendhere").append(div)
             m_names[monthnumber] == "December" ? yearnumber++ : yearnumber + 0;
          }
    

Related Articles