javascriptangularflatpickr

Flatpickr onChange event in range mode is always giving selectedDates in sequencial order. I want the seleted dates to be received as per my selection


I'm using a flatPickr instance to get range of seletedDates. But in whatever order i select the range i.e; ([startDate 1st -> endDate last] or [endDate 1st & startDate last]) the selected dates range is always given in sequential order.

I dont want the selectedDates range in sequential oder. I want the dates to be fetched as per my selection so that i can do some calculation. below is my code.

flatpickr(element, {
    mode: "range",
    dateFormat: "d-m",
    maxDate: "today",
    onChange: function(selectedDates, dateStr, instance) {
        if (selectedDates.length > 1) {
        // the selectedDate param will always give the date range in array sequence.
        // Ex: if i selected Mar 1st 2023 1st & then selects Jan 1st 2023 next, the selectedDates Array will be [Jan1st, Mar1st]
        // I want the selectedDates Array to be [Mar1st, Jan1st] so that if i calculate the difference between them i'll get -ve value so that i can perform a different calculation.
            if (moment(selectedDates[1]).diff(selectedDates[0], 'days') > 90) {                               
                instance.setDate([selectedDates[0], new Date(selectedDates[0]).fp_incr(90)]);
            }
        }
    }
});

So, requesting someone to please help me achieve this.


Solution

  • You must store the initial data in a variable outside of the flatpickr function. when the array length of selectedDates.length is equal to 1 you know that this is the first date. you can then store it in your variable so that you always know which date the user first clicked on

    $(function() {
    
      let first_clicked_date; // Store variable outside function.
      
      $(".flatpick").flatpickr({
        mode: "range",
        dateFormat: "d-m",
        maxDate: "today",
        onChange: function(selectedDates, dateStr, instance) {
          // if selectedDates length equal to 1 then add it to variable "first_clicked_date"
          first_clicked_date = selectedDates.length === 1 ? selectedDates[0] : first_clicked_date;
          console.log(`First click is: ${first_clicked_date}`);
    
          if (selectedDates.length > 1) {
            // Your code
          }
        }
      });
    });
    <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>
    
    <input class="flatpick">