Search code examples
javascriptjqueryflatpickr

Flatpickr populate div text with chosen date


My .auto-input function populates the container div .text when you type in an input, but it won't take the value in the flatpickr input field and populate the .flatpickr div text when you choose a date.

How do I get the text inside of .flatpickr to populate based on the input from #flapickr?

$('.auto-input').keyup(function() {
  var $this = $(this);
  $('.' + $this.attr('id') + '').html($this.val());
});
var example = flatpickr("#flatpickr", {
  locale: "en",
  altInput: true,
  dateFormat: "d-m-Y",
  minDate: "1950-01-01",
  allowInput: false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-wrapper">
  <input class="auto-input" id="text" type="text" /><br/>
  <input class="auto-input" id="flatpickr" type="text" placeholder="deal expires on...">
</div>
<div class="input-fill-holder">
  <div class="text"></div>
  <div class="flatpickr">Fill Date Here</div>
</div>
<link href="https://npmcdn.com/flatpickr/dist/flatpickr.css" rel="stylesheet" type="text/css">
<link href="https://npmcdn.com/flatpickr/dist/themes/airbnb.css" rel="stylesheet" type="text/css">
<script src="https://npmcdn.com/flatpickr/dist/flatpickr.min.js"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/fr.js"></script>


Solution

  • You have to add onChange or onClose event hook and then update the .flatpickr div accordingly. Read more here: https://flatpickr.js.org/events/#hooks

    Here is the fiddle: https://jsfiddle.net/yhn4peey/4/

    Here is the example:

    $('.auto-input').keyup(function() {
      var $this = $(this);
      $('.' + $this.attr('id') + '').html($this.val());
    });
    var example = flatpickr("#flatpickr", {
      locale: "en",
      altInput: true,
      dateFormat: "d-m-Y",
      minDate: "1950-01-01",
      allowInput: false,
      onChange: function(selectedDates, dateStr, instance) {
            $(".flatpickr").html(dateStr);
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="input-wrapper">
      <input class="auto-input" id="text" type="text" /><br/>
      <input class="auto-input" id="flatpickr" type="text" placeholder="deal expires on...">
    </div>
    <div class="input-fill-holder">
      <div class="text"></div>
      <div class="flatpickr">Fill Date Here</div>
    </div>
    <link href="https://npmcdn.com/flatpickr/dist/flatpickr.css" rel="stylesheet" type="text/css">
    <link href="https://npmcdn.com/flatpickr/dist/themes/airbnb.css" rel="stylesheet" type="text/css">
    <script src="https://npmcdn.com/flatpickr/dist/flatpickr.min.js"></script>
    <script src="https://npmcdn.com/flatpickr/dist/l10n/fr.js"></script>