Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Date Picker - disable past dates

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.

like image 458
Harsha M V Avatar asked Dec 02 '11 12:12

Harsha M V


People also ask

How do I disable date range picker?

DateRangePicker can be inactivated on a page, by setting enabled value as false that will disable the component completely from all the user interactions including in form post.

How do I set the calendar to not allow dates before today's date?

By setting a minimum selectable date on your DatePicker using the setMinDate(…) method, the dates before that will become greyed out and not selectable in the Calendar.


2 Answers

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/

like image 192
Nicola Peluchetti Avatar answered Sep 22 '22 04:09

Nicola Peluchetti


Declare dateToday variable and use Date() function to set it.. then use that variable to assign to minDate which is parameter of datepicker.

var dateToday = new Date();  $(function() {     $( "#datepicker" ).datepicker({         numberOfMonths: 3,         showButtonPanel: true,         minDate: dateToday     }); }); 

That's it... Above answer was really helpful... keep it up guys..

like image 29
Sachin Avatar answered Sep 20 '22 04:09

Sachin