Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict date in jquery datepicker based on another datepicker or textbox

I have two text boxes with a datepicker hooked up to them. The text boxes are for start date and end date. The first datepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datepicker so that it cannot choose a date before the date chosen in the first date picker? For example: If today is 12/11/10 and I choose 12/15/10 in the first datepicker, then the second date picker shouldn't be able to choose anything before 12/15/10.

Heres what I have so far:

$("#txtStartDate").datepicker({ minDate: 0 });
$("#txtEndDate").datepicker({});
like image 559
The Muffin Man Avatar asked Dec 12 '10 00:12

The Muffin Man


2 Answers

For example, in this sample code, startDatePicker is selected as 2010-12-12, change event of startDatePicker sets the minDate of endDatePicker 2010-12-13. It locks the cells before this date. This is a sample for what @Victor mentioned..I hope it helps...Regards...Ozlem.

$("#startDatePicker").datepicker({ 
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    minDate: new Date(),
    maxDate: '+2y',
    onSelect: function(date){

        var selectedDate = new Date(date);
        var msecsInADay = 86400000;
        var endDate = new Date(selectedDate.getTime() + msecsInADay);

       //Set Minimum Date of EndDatePicker After Selected Date of StartDatePicker
        $("#endDatePicker").datepicker( "option", "minDate", endDate );
        $("#endDatePicker").datepicker( "option", "maxDate", '+2y' );

    }
});

$("#endDatePicker").datepicker({ 
    dateFormat: 'yy-mm-dd',
    changeMonth: true
});
like image 61
user403295 Avatar answered Oct 16 '22 03:10

user403295


Update:

The approach above set the minDate only on creation time. I used the onSelect event to change the minDate option of the second datepicker like this:

$("#txtStartDate").datepicker({
  showOn: "both",       
  onSelect: function(dateText, inst){
     $("#txtEndDate").datepicker("option","minDate",
     $("#txtStartDate").datepicker("getDate"));
  }
});
like image 44
Nguyen Van Long Avatar answered Oct 16 '22 02:10

Nguyen Van Long