With setting the deadline on the dynamic datepicker?

Asked

Viewed 106 times

-1

I have to set a maximum date for the calendar in a dynamic way that is the month MUST be from the CURRENT and at most ONE year after the month CURRENT.

$(document).ready(function() {
   $(".datepicker").datepicker({
      dateFormat: 'dd/mm/yy',
      changeMonth: true,
      changeYear: true,
      yearRange: "2019:2020"
   });
})
  • 1

    Would it be from the first day of the current month to the last day of the month 1 year from now? Ex.: 01/10/2019 to 31/10/2020?

  • From today until a year ahead: 31/10/2020

1 answer

1


Just take the current month and the current year and use a Setter to change the options minDate and maxDate of the component.

The minDate is simple, just put the value "0" that the initial date will be today’s date. In the case of maxDate, will have to pick up the current month and the current year through an object new Date():

var hoje = new Date(); // data de hoje
var mesAtual = hoje.getMonth()+1; // mês atual
var anoFinal = hoje.getFullYear()+1; // ano atual +1 = ano seguinte

As today is 10/04/2019, the above values will be:

mesAtual -> 10
anoFinal -> 2020

So you put these values into another object new Date() in the option maxDate:

new Date(anoFinal, mesAtual, 0)

That one 0 means it will go until the last day of the month.

Would that be the code:

$(document).ready(function() {
   $("#datepicker").datepicker({
      dateFormat: 'dd/mm/yy',
      changeMonth: true,
      changeYear: true
   });
   
   var hoje = new Date();
   var mesAtual = hoje.getMonth()+1;
   var anoFinal = hoje.getFullYear()+1;
   
   $("#datepicker").datepicker( "option", {
      "minDate": "0",
      "maxDate": new Date(anoFinal, mesAtual, 0)
   });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" id="datepicker">

These settings are well explained in documentation.

  • grateful for the response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.