javascriptjqueryjquery-uidatepicker

JQuery datepickers- setting end date from a start date


There are two Jquery datepickers in use, StartDate and EndDate

<input id="StartDate" class="datepicker setNext hasDatepicker" type="text" value="13/02/2015" name="StartDate">
<input id="EndDate" class="datepicker hasDatepicker" type="text" value="15/02/2015" name="EndDate">

When the StartDate datepicker is selected I want the EndDate datepickers to be the StartDate + 1 Day, and to make it so that earlier dates cannot be selected in EndDate than are in StartDate.

I have this code:

$(function () {
    $(".datepicker").datepicker({
        dateFormat: 'dd/mm/yy',
        onSelect: function( selectedDate ) {
            if(this.id == 'StartDate') {
                var minDate = selectedDate + 1;
                $('#to').datepicker("option", "minDate", minDate);

            }
        }
   });
});

So it hits the onSelect ok, but then the adding 1 to the date doesn't work (I just get the datestring with a 1 on the end, so '31/12/20141').

I have also tried the following in the OnSelect, assuming that selectedDate was a string not a date type:

                var minDate = new Date(selectedDate);
                var tomorrow = new Date();
                tomorrow.setDate(minDate.getDate() + 1);
                $('#to').datepicker("option", "minDate", tomorrow);

minDate ends up being an Invalid Date, as does tomorrow. I can't work out how to set dates from the string. Trying something along the lines of:

var minDate = selectedDate.getDate();

Gets me an 'Uncaught TypeError: undefined is not a function'.

Using JQuery 1.11.1, UK date formats of dd/mm/yyyy.


Solution

  • If you want to change the datepicker date of another datepicker adding a day, you can do something like this:

    Note that selectedDate is in format dd/mm/YYYY which is not a valid string date format to use in Date constructor. You have then to parse it.

            var arr = selectedDate.split("/");
            var date = new Date(arr[2]+"-"+arr[1]+"-"+arr[0]);
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();
            var minDate = new Date(y, m, d + 1);
            $("#EndDate").datepicker('setDate', minDate);
    

    Here you have a working example fiddle