简体   繁体   中英

How to disable previous dates(in the enddate field) based on the date the user selected on the startdate field? (using input type "date" & javascript)

I have two input fields:

<input type="date" id="start">

and

<input type="date" id="end">

Is there a way I could disable the previous dates on the "end" input field based on the date the user has selected on the "start" input.

Eg: If the user selects "2022/01/11" on the start input field, it should automatically disable all previous dates on the end input field (user should only be allowed to select dates from 2022/01/11 or greater).

All this using javascript.

What I have tried:

$(function(){
    var dtToday = new Date();
    
    var month = dtToday.getMonth() + 1;
    var day = dtToday.getDate();
    var year = dtToday.getFullYear();
    if(month < 10)
        month = '0' + month.toString();
    if(day < 10)
        day = '0' + day.toString();
    
    var minDate= year + '-' + month + '-' + day;
    
    $('#txtDate').attr('min', minDate);
});

Which works but only for one input field.

Thanks in advance.

You could handle the "change" event of the start date input and update the min attribute of the end date input with the value of the start date input:

 $("#start").change(function(){ $("#end").prop("min", $(this).val()); $("#end").val(""); //clear end date input when start date changes });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="date" id="start" /> <input type="date" id="end" />

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