flatpickr

Flatpickr when start date is selected, disable all dates before start date so end date can't select a date before


I have two date pickers. Start Date and End Date.

If i pick todays date for example using the start date picker, i would like all dates before that disabled so that when i click end date picker i cannot select any dates before the start date.

All i have is the Flatpickr setup and i have tried the disable function, im just not sure what to do.

flatpickr('#startDate', {
  enableTime: false,
  allowInput: true,
  dateFormat: "m/d/y",
  disableMobile: "true",
  disable: [
    function(date) {
      // saturdays
      return date.getDay() === 6;
    },
    function(date) {
      // sundays
      return date.getDay() === 0;
    }
  ]
});

flatpickr('#endDate', {
  enableTime: false,
  allowInput: true,
  dateFormat: "m/d/y",
  disableMobile: "true"
  // "plugins": [new rangePlugin({ input: "#endDate" })]
});

Solution

  • You can do this in two ways:

    Option 1: Use Flatpickr's MinDate option to specify minimum/earliest date allowed for selection

    const start_date = flatpickr("#start_date", {
      dateFormat: 'Y-m-d',
      onChange: function(sel_date, date_str) {
        end_date.set("minDate", date_str);
      }
    });
    
    const end_date = flatpickr("#end_date", {
      dateFormat: 'Y-m-d'
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.js"></script>
    
    <label for="start_date">Start:</label>
    <input type="text" id="start_date" name="start_date">
    
    <label for="endDate">End:</label>
    <input type="text" id="end_date" name="end_date">

    Option 2:

    You can also use the Flatpickr range function, so the dates will always be consecutive.

    const range_flatpickr = flatpickr("#range_flatpickr", {
      dateFormat: 'Y-m-d',
      mode: "range"
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.js"></script>
    
    <label for="range_flatpickr">Range:</label>
    <input type="text" id="range_flatpickr" name="range_flatpickr" style="width:200px">