0

I want to limit the year in the Select Input Type to only show 5 years from now and the year before

<div class="col-12">
     <select class="form-select bg-light border-0" style="height: 55px;">
             <option selected>Years</option>
             <option value="2018">2018</option>
             <option value="2019">2019</option>
             <option value="2020">2020</option>
             <option value="2021">2021</option>
             <option value="2022">2022</option>
      </select>
</div>

for example as above, but using dynamic code with PHP or javascript, please help me

Fazan
  • 5
  • 3
  • This is how to get previous years with Javascript. ```const currentYear = new Date().getFullYear(); // 2020 const previousYear = currentYear-1; console.log(previousYear); // 2019```. Same goes with getting the next. Now you need to make a for loop to create option with ```createElement()```. For more info: https://reactgo.com/javascript-get-previous-year/ https://www.tutorialspoint.com/how-to-add-a-new-element-to-html-dom-in-javascript – NathanaelDousa Jun 23 '22 at 08:34
  • Does this answer your question? [Can I use an HTML input type "date" to collect only a year?](https://stackoverflow.com/questions/34676752/can-i-use-an-html-input-type-date-to-collect-only-a-year) – smitop Jun 23 '22 at 13:01

2 Answers2

0

$(function () { 
 
  const currentYear = new Date().getFullYear();
  

  var oldYearValue=0, newYearValue=0; 
for (var i = 5; i >= 0; i--) {
   debugger
   oldYearValue= currentYear-i;
  
  if(oldYearValue != new Date().getFullYear()){
    
  
     $('#select1').append('<option value='+oldYearValue+'>'+oldYearValue+'</option>');
  }
  if (i==0){
    
    for (var j = 0; j <= 5; j++) {
   
   newYearValue= currentYear+j;
     $('#select1').append('<option value='+newYearValue+'>'+newYearValue+'</option>');
}
  }
}
   
 
 
  
  });
<script type="text/javascript" src="js/script.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div class="col-12">
     <select class="form-select bg-light border-0" id="select1" style="height: 55px;">
             <option selected>Years</option>
       
      </select>
</div>

See Result Here

Mati Ullah Zahir
  • 168
  • 1
  • 3
  • 13
0

Might be this help for you in PHP

<div class="col-12">
 <select class="form-select bg-light border-0">
         <option disabled selected>Years</option>
         <?php
         for ($i = 4; $i >= 0; $i--) {
           $year_= date('Y', strtotime("-$i year"));
           echo '<option value="'.$year_.'">'.$year_.'</option>';
         }?>
  </select>