Search code examples
jqueryjquery-uijquery-ui-datepicker

jquery datepicker date restriction not working


I try to restrict a picker by value from another picker. I looked other questions here but they seem to be outdated and not work

What I do is following

<p><input type="text" id="startdatepicker"></p>
<p><input type="text" id="enddatepicker"></p>

$(function() {
    $("#startdatepicker")
        .datepicker({ minDate: -1, maxDate:"" })
        .datepicker("option", "dateFormat", "dd.mm.yy");
});

$(function() {
    $("#enddatepicker")
        .datepicker({
            minDate: $("#startdatepicker").datepicker("getDate"), 
            maxDate: ""
        })
        .datepicker("option", "dateFormat", "dd.mm.yy");
});

How to do this correctly ?


Solution

  • This is fairly straightforward to accomplish:

    $(function() {
        $("#startdatepicker, #enddatepicker")
            .datepicker({
                minDate: -1,
                dateFormat: "dd.mm.yy",
             })
         ;
    
        $('#enddatepicker')
            .datepicker('option', 'disabled', true);
    
        $('#startdatepicker').on('change', function(){
            var datestamp = this.value.split('.');
    
            datestamp = new Date(
                +datestamp[2],
                +datestamp[1],
                +datestamp[0]
            );
    
            if (!datestamp) return false;
    
            $('#enddatepicker')
                .datepicker('option', 'disabled', false)
                .datepicker('option', 'minDate', datestamp)
            ;
        });
    });
    

    https://jsfiddle.net/zvc1p8xk/