简体   繁体   中英

How do I set Min Date in Datepicker from another Datepicker?

I am currently adding validation to my date pickers and am having trouble setting the min date in the to date picker to be whatever was chosen in the from date picker. Ie if 12-3-15 is selected then the minimum date in the to date picker is 12-3-15. Here is the code I am using:

$("#from").datepicker({
            defaultDate: new Date(),
            minDate: new Date(),
            onSelect: function(dateStr) 
            {
            fromDate = new Date(dateStr);
            }
        });

$('#to').datepicker({
            defaultDate: new Date(),
            minDate: ("#from" + "1D"), (<- HERE)
            onSelect: function(dateStr) {
            toDate = new Date(dateStr);

                // Converts date objects to appropriate strings
                fromDate = ConvertDateToShortDateString(fromDate);
                toDate = ConvertDateToShortDateString(toDate);
        });

Does anybody know how I could achieve this?

Please check this working fiddle

JSFiddle

Use option to set the minDate to the second datepicker

$("#from").datepicker({
        defaultDate: new Date(),
        minDate: new Date(),
        onSelect: function(dateStr) 
        {         
            $("#to").val(dateStr);
            $("#to").datepicker("option",{ minDate: new Date(dateStr)})
        }
    });

The answer is good but you need to destroy the datepicker of the $to because if not the $to datepicker have still the first date what you select, and remove the option in $to datepicker, this work for me, you not need to make other function for $to.

$("#from").datepicker({
    defaultDate: new Date(),
    minDate: new Date(),
    onSelect: function(dateStr) 
    {         
        $("#to").datepicker("destroy");
        $("#to").val(dateStr);
        $("#to").datepicker({ minDate: new Date(dateStr)})
    }
});

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