Search code examples
javascriptvue-componentflatpickr

How to add onKeyDown event for a flatpickr element?


I would like to add onKeyDown event for a flatpickr element in my page. Currently I have the below code, but this is not working. The event is not getting fired. Any help is appreciated.

const dob = flatpickr('#date_of_birth', {
    allowInput: true,
    altInput: true,
    altFormat: "m-d-Y",
    dateFormat: "m-d-Y",
    wrap: true,
});

window.onload = function() {
    if(dob) {
        dob.config.onKeyDown.push(function(selectedDates, dateStr, instance) {
            console.log("Date Value: " + dateStr); // not printed
        });
    }
}

Edit: I am using Flatpickr as a Vue component in my application.


Solution

  • Finally I was able to get the onKeyDown event working with the below code:

    const dob = flatpickr('#date_of_birth', {
        allowInput: true,
        altInput: true,
        altFormat: "m-d-Y",
        dateFormat: "m-d-Y",
        wrap: true,
        onKeyDown: (selectedDates, dateStr, instance, event) => {
            if(event.keyCode != 8) {
                var ele = document.activeElement;
                var val = ele.value;
                  
                if (val.length == 2 || val.length == 5) {
                    val += '-';
                }
    
                ele.value = val;
                ele.dispatchEvent(new Event('input'));
              }
        },
    });
    

    Hope it helps someone out there in future.