简体   繁体   中英

limit a select dates in date range picker and disable other days javascript Set maximum date dynamically

Using pure JavaScript build methods without any library or plugin (Dayjs, Moment.Js or date-fns).

Allow to choose 2 months (60 days) only in date range picker dynamically set for max date.

First I choose start date as today's date or any date on that day. Then the end date to choose is only within 2 months (60 days). Other dates must be in disabled state.

HTML min and max attributes not possible to use. In that have to set the hardcoded date for min and max date. Should be dynamically set for max date in date picker and disable other days.

<div class="container">
    <form id="form" class="form">
        <div class="form__control">
            <input type="date" id="input__date" />
                <small class="erorr__Msgs">Select date within 60 days only </small>         
        </div>
        <button class="get__Date" onclick="rangeDate()">Submit</button>
    </form>
</div>

function rangeDate() {

    let selectedDate = document.querySelector("#input__date").value;
    console.log("selectedDate:" + selectedDate);
    var daystimestamp = new Date().getTime() + (60 * 24 * 60 * 60 * 1000)
                                              // day hour min sec msec
    if(daystimestamp < selectedDate) {
    
    } else(daystimestamp>= selectedDate){
          }
}

I add the jquery code to the better understand the question:

$("").datepicker({
    dateformat:"dd-m-yyy",
    maxDate:'3M',
    minDate:'-3M'
}); 

maxDate is set to 3M ie 3 months (90 days). It is possible to set days like this in pure javascript without any library or plugin.

And the the max date should be carry forwarded.

Example:

If selected in Dec 1 2020 then max date selection should not exceed more than 2 months (60 days) dates after 1 feb 2021 should be disabled.

Here's a code sample where I defined in the code the min and max date of the input[type=date] . You can change minDate to be every day you want, and the maxDate will be defined accordingly with + 60 days.

 let dtElem = document.getElementById('datetime'); let minDate = new Date(); let maxDate = new Date(); maxDate.setDate(minDate.getDate() + 60); dtElem.min = formatDate(minDate); dtElem.max = formatDate(maxDate); console.log(formatDate(minDate)); console.log(formatDate(maxDate)); function formatDate(date) { let dd = String(date.getDate()).padStart(2, '0'); let mm = String(date.getMonth() + 1).padStart(2, '0'); let yyyy = date.getFullYear(); return `${yyyy}-${mm}-${dd}`; }
 <input type="date" id="datetime">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM