jqueryjquery-ui-datepicker

Jquery datepicker not setting 90days or 3months from the month selected in Jquery


I have 2 dates fromDate and ToDate in which I want to implement a logic where if in

FromDate is selected todays date, in ToDate the date should be active or enabled till previous 90 days or 3 months. Also max date in both textbox should be current date

Here is the code which I tried

$(function() {
  $("#fromDate").datepicker({ //
    dateFormat: 'dd/mm/yy',
    changeMonth: true,
    changeYear: true,
    maxDate: "+90y",
    defaultDate: null
  }).datepicker("setDate", new Date());
  
  $("#toDate").datepicker({
    dateFormat: 'dd/mm/yy',
    changeMonth: true,
    changeYear: true,
    defaultDate: null,
    maxDate: 0,
    onSelect: function() {
      //$('#fromDate').datepicker('option', 'minDate', $("#toDate").datepicker("getDate"));
    }
  }).datepicker("setDate", new Date());
});
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>


<input id="fromDate" type="text" value="16/02/2024">
<input id="toDate" type="text" value="16/02/2024">


Solution

  • Based on the wording in the requirements and the attempted code:

    limit from date to be 90 days before to date when to date is changed

    The attempt was very close, just need to subtract the days, eg using this answer

        onSelect: function() {
            let d = $("#toDate").datepicker("getDate");
          d.setDate(d.getDate() - 90);
          $('#fromDate').datepicker('option', 'minDate', d);
        }
    

    Updated snippet, using 3 days so it's easier to test:

    $(function() {
      $("#fromDate").datepicker({ //
        dateFormat: 'dd/mm/yy',
        changeMonth: true,
        changeYear: true,
        maxDate: "+0",
        defaultDate: null
      }).datepicker("setDate", new Date());
      
      $("#toDate").datepicker({
        dateFormat: 'dd/mm/yy',
        changeMonth: true,
        changeYear: true,
        defaultDate: null,
        maxDate: 0,
        onSelect: function() {
            let d = $("#toDate").datepicker("getDate");
          d.setDate(d.getDate() - 3);
          $('#fromDate').datepicker('option', 'minDate', d);
        }
      }).datepicker("setDate", new Date());
    });
    <link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
    
    
    <input id="fromDate" type="text" value="16/02/2024">
    <input id="toDate" type="text" value="16/02/2024">