jQuery Date Picker - disable past dates

Harsha M V picture Harsha M V · Dec 2, 2011 · Viewed 317.3k times · Source

I am trying to have a date Range select using the UI date picker.

in the from/to field people should not be able to view or select dates previous to the present day.

This is my code:

$(function() {
    var dates = $( "#from, #to" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 1,
        onSelect: function( selectedDate ) {
            var option = this.id == "from" ? "minDate" : "maxDate",
                instance = $( this ).data( "datepicker" ),
                date = $.datepicker.parseDate(
                    instance.settings.dateFormat ||
                    $.datepicker._defaults.dateFormat,
                    selectedDate, instance.settings );
            dates.not( this ).datepicker( "option", option, date );
        }
    });
});

Can some one tell me how to disable dates previous the to the present date.

Answer

Nicola Peluchetti picture Nicola Peluchetti · Dec 2, 2011

You must create a new date object and set it as minDate when you initialize the datepickers

<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/>

var dateToday = new Date();
var dates = $("#from, #to").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    minDate: dateToday,
    onSelect: function(selectedDate) {
        var option = this.id == "from" ? "minDate" : "maxDate",
            instance = $(this).data("datepicker"),
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
        dates.not(this).datepicker("option", option, date);
    }
});

Edit - from your comment now it works as expected http://jsfiddle.net/nicolapeluchetti/dAyzq/1/