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

Jåcob picture Jåcob · May 4, 2013 · Viewed 61.5k times · Source

I am using Jquery date picker and I have the following code where when user selects a date, the field below is populated with date +1

$('#dt2').datepicker({
        dateFormat: "dd-M-yy" 
    });

$("#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);

I would like to restrict dates in dt2 field which should not be below the date in dt1 field. E.g. If date selected in dt1 is 01-May-2013, then user is allowed to pick date after 01-May-2013, not less than 02-May-2013

How can I restrict date picking in date field 2?

Answer

SirDerpington picture SirDerpington · May 4, 2013

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