Jquery datepicker restrict dates in second date field based on selected date in first date field

I created a jsfiddle for you.
I’m not a 100% sure if it’s “foolproof” but to prevent users from manually typing a date you could set the inputs to readonlye.g.

<input type="text" id="dt1" readonly="readonly">

At the moment I check the dt2 onClose and if its date is below dt1s date I correct it.
Also if a date is selected in dt1 the minDate of dt2 is set to dt1 date +1.

$(document).ready(function () {

    $("#dt1").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 0,
        onSelect: function (date) {
            var date2 = $('#dt1').datepicker('getDate');
            date2.setDate(date2.getDate() + 1);
            $('#dt2').datepicker('setDate', date2);
            //sets minDate to dt1 date + 1
            $('#dt2').datepicker('option', 'minDate', date2);
        }
    });
    $('#dt2').datepicker({
        dateFormat: "dd-M-yy",
        onClose: function () {
            var dt1 = $('#dt1').datepicker('getDate');
            var dt2 = $('#dt2').datepicker('getDate');
            //check to prevent a user from entering a date below date of dt1
            if (dt2 <= dt1) {
                var minDate = $('#dt2').datepicker('option', 'minDate');
                $('#dt2').datepicker('setDate', minDate);
            }
        }
    });
});

See the jsfiddle

Leave a Comment