Search code examples
javascripthtmldatedatetimedatepicker

Limiting Date Picker (from today) - HTML


I have been looking around on this page (among other forums) in search of an answer for limiting a date picker to 14 days from the day a user accesses the page. Built into the date picker is an option for 'todays date' which is auto configured and sets the date option to todays DD/MM/YY so I gather this can be achieved. What I aim for is every date after 14 days from 'today' to be greyed out and not selectable. I could further develop this so that no dates prior to 'today' can also be selected, but achieving a limit of 14 days after 'today' would be great for now.

I'm familiar with max-date and min-date which require a precise DD/MM/YY format setting boundaries between the listed dates. I require something like 'max-date: today + 14'


Solution

  • I require something like 'max-date: today + 14'

    This is basically your answer, i.e. "set the max attribute to today + 14 and the min attribute to today". Fairly straightforward to do in JavaScript:

    const datePicker = document.getElementById("date-picker");
    
    datePicker.min = getDate();
    datePicker.max = getDate(14);
    
    // Borrowed from https://stackoverflow.com/a/29774197/7290573
    function getDate(days) {
        let date;
    
        if (days !== undefined) {
            date = new Date(Date.now() + days * 24 * 60 * 60 * 1000);
        } else {
            date = new Date();
        }
    
        const offset = date.getTimezoneOffset();
    
        date = new Date(date.getTime() - (offset*60*1000));
    
        return date.toISOString().split("T")[0];
    }
    <input id="date-picker" type="date" autocomplete="off" />