Search code examples
javascriptdatepickerlaravel-livewirealpine.js

vanillajs-datepicker does not set input value, no change event triggered on date click


I'm using this datepicker and I like it but its not triggering the change event on an input after I click a date.

Here is my code
I tested this on jsFiddle

const elem = document.querySelector('input[name="foo"]');
const datepicker = new Datepicker(elem, {
  autohide: true,
  todayHighlight: true,
  format: "yyyy-mm-dd",
});

elem.addEventListener("change", function(e) {
  console.log(e.target.value);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/datepicker.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/datepicker-full.min.js"></script>

<input type="text" name="foo">

When I click the specific date on the datepicker the change event is not triggered.

I need help with this.

I'm also using it with livewire and alpine but after clicking the date the change even is not triggered. here is my laravel code
code

When I tested pickaday it works.

How can I work around this or make it to trigger the change even on vanillajs datepicker.

Thanks in advance.


Solution

  • Your library won't trigger a native event like onchange which is why is not working. You have to use the library custom event instead

    Info in the documentation changedate

    const elem = document.querySelector('input[name="foo"]');
    const datepicker = new Datepicker(elem, {
      autohide: true,
      todayHighlight: true,
      format: "yyyy-mm-dd",
    });
    
    elem.addEventListener("changeDate", function (e) {
      console.log(e.target.value);
    });
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/datepicker.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/datepicker-full.min.js"></script>
    <input type="text" name="foo">