Search code examples
javascriptjqueryflatpickr

flatpicker1 onChange event to set minDate on flatpicker2. How?


I have just downloaded flatpickr which is a datetime picker in javascript.

A few quick references: Examples, Formating tokens & Events

I am trying to figure out how to use 2 datetime pickers which need to depend on one another to avoid data range selection errors.

So far I have:

Made sure user can only choose dates in 2019. The time for inputText1 is always 00:00:00.

To do:

Set inputText2 minDate equal to inputText1 minDate using inputText1 onChange event.

inputText2 times must always end in 23:59:59

$(document).ready(function(){

  $("#inputText1").flatpickr({
    minDate: "2019-01",
    maxDate: "2019-12",
    dateFormat: "Y-m-d H:i:S",
    // When this input changes, we set a min start date for input2 always equal or greater than from date.
    onChange: function(selectedDates, dateStr, instance) {
      $("#reportFromCustom").html(dateStr);

      // Any ideas?
      //$("#inputText2").flatpickr({ minDate: dateStr });
    }

  });

  $("#inputText2").flatpickr({
    dateFormat: "Y-m-d 23:59:59",
    // When this input changes, we set a min start date for input2 always equal or greater than from date.
    onChange: function(selectedDates, dateStr, instance) {
      $("#reportToCustom").html(dateStr);
    }

  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>


<table>
  <th>
    <tr>
    <strong>Select range</strong>
    </tr>
  </th>
  <tr>
  <td>From: <input type="text" id="inputText1"></td>
  <td>To:<input type="text" id="inputText2"></td>
  </tr>
</table>


Solution

  • You are searching for set() method

    set(option, value)
    

    var date1 = $("#inputText1").flatpickr({
      minDate: "2019-01",
      maxDate: "2019-12",
      dateFormat: "Y-m-d H:i:S",
      onChange: function(selectedDates, dateStr, instance) {
        date2.set('minDate', dateStr)
      }
    });
    
    var date2 = $("#inputText2").flatpickr({
      dateFormat: "Y-m-d 23:59:59",
      onChange: function(selectedDates, dateStr, instance) {
        date1.set('maxDate', dateStr)
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    
    <table>
      <th>
        <tr>
          <strong>Select range</strong>
        </tr>
      </th>
      <tr>
        <td>From: <input type="text" id="inputText1"></td>
        <td>To:<input type="text" id="inputText2"></td>
      </tr>
    </table>