Search code examples
javascriptjqueryflatpickr

How to set conditional config options in flatpickr


I am successfully using flatpickr as my favorite date picker, but now I have to make the "defaultDate" input conditional.

if(defDateExists){
    defaultDate: ucheckout,
}

That breaks my function. I have no idea how to use options conditionally. Please help. Thanks!

function _flattie() {
    const fpx = flatpickr(".flatpickr", {
        minDate: new Date().fp_incr(1), // 1 days from now
        dateFormat: "Y-m-d",
        disableMobile: "true",
        if(defDateExists){
            defaultDate: checkout,
        }
        monthSelectorType: "static",
        inline: true,
        onChange: function() {
            selectedDate = new Date(tempDate).toString("yyyy-MM-dd");
            stringDate = new Date(tempDate).toString("MMM dS yyyy"); 
            }
        }
    });
}

Solution

  • Try with ternary conditionals:

    function _flattie() {
    const fpx = flatpickr(".flatpickr", {
        minDate: new Date().fp_incr(1), // 1 days from now
        dateFormat: "Y-m-d",
        disableMobile: "true",
        defaultDate: defDateExists ? checkout : null,
        monthSelectorType: "static",
        inline: true,
        onChange: function() {
            selectedDate = new Date(tempDate).toString("yyyy-MM-dd");
            stringDate = new Date(tempDate).toString("MMM dS yyyy"); 
            }
        }
    });}