Joey Jaison
Joey Jaison

Reputation: 65

Get dynamic Year range and append in option in selection list

I want a specific year range to be dynamic. Currently it is a fixed range. For example, the current year is 2020 so I want to get range 2015-2025. If the current year is 2021 the range must be 2016-2026. How can I do that?

$(document).ready(function() {
  var y = 2015;
  for (i = 0; i <= 10; i++) {
    $("#myselectYear").append(new Option(y, y));
    y = parseInt(y) + parseInt(1);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-body">
  <div class="form-group">
    <label>Year</label>
    <select id="myselectYear">
      <option value="">-Select-</option>
    </select>
  </div>
  <div class="col-md-4">
    <div class="form-group">
      <label>Month</label>
      <select id="myselectMonth">
        <option value="">-Select-</option>
      </select>
    </div>
  </div>
</div>

Upvotes: 1

Views: 784

Answers (2)

Sandeep Modak
Sandeep Modak

Reputation: 842

get the current date and find the current year out of it.

$(document).ready(function() {
  //get current date
  var d = new Date();
  //get current year out of it
  var n = d.getFullYear();

  var y = n-5;
  for (i = 0; i <= 10; i++) {
    $("#myselectYear").append(new Option(y, y));
    y++;
  }
});

Try this fiddle

Upvotes: 1

Vaibhav
Vaibhav

Reputation: 1473

getFullYear() gives you current year.

$(document).ready(function() {
  var minYear = new Date().getFullYear() - 5;
  let y = 0;
  for (i = 0; i <= 10; i++)
    y = minYear + 1;
    $("#myselectYear").append(new Option(y, y));
  }
});

Upvotes: 1

Related Questions