jQuery Date Picker - disable past dates

2019-01-01 15:03发布

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.

14条回答
皆成旧梦
2楼-- · 2019-01-01 16:00

"mindate" attribute should be used to disable passed dates in jquery datepicker.

minDate: new Date() Or minDate: '0' is the key for this.

Ex:

$(function() {
    $( "#datepicker" ).datepicker({minDate: new Date()});
});

OR

$(function() {
  $( "#datepicker" ).datepicker({minDate: 0});
});
查看更多
十年一品温如言
3楼-- · 2019-01-01 16:01

I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)

We are using beforeShowDay method of jQuery UI datepicker plugin.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var NotBeforeToday = function(date) {
		var now = new Date(); //this gets the current date and time
		if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )
			return [true,""];
		if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))
			return [true,""];
		if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))
			return [true,""];
		return [false,""];
	}


jQuery("#datepicker").datepicker({
		beforeShowDay: NotBeforeToday
    });

enter image description here

Here today's date is 15th Sept. I have disabled Saturday and Sunday.

查看更多
登录 后发表回答