Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Multiple months disable moving to first on select

I am having an issue with this jquery (JSFiddle Link), It allows me to select a range of dates, and when I select a date, it moves the month of the date that I select to the first month. For example I select a date from month 2, the datepicker moves that month to the first month in the list of displayed months. How can I disable that? I just want it to stay where it is.

$(".date-picker").datepicker({
    numberOfMonths: 3,
    beforeShowDay: function(date) {
        var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#date-from").val());
        var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#date-to").val());
        return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
    },
    onSelect: function(dateText, inst) {
        var date1 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#date-from").val());
        var date2 = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $("#date-to").val());
        if (!date1 || date2) {
            $("#date-from").val(dateText);
            $("#date-to").val("");
            $(this).datepicker("option", "minDate", dateText);
        } else {
            $("#date-to").val(dateText);
            $(this).datepicker("option", "minDate", null);
        }
    }
});

Upvotes: 1

Views: 794

Answers (2)

Fibman
Fibman

Reputation: 126

Take also in account that it may change year too. In addition to Remy and johannes answer, you may also like to add:

var drawYear = $(this).data().datepicker.drawYear;

...

$(this).data().datepicker.drawYear = drawYear;

Upvotes: 0

johannes
johannes

Reputation: 61

As Ramy said, it's because of the re-rendering after setting the min date.

To prevent it from jumping to the month of the selected date to the first position, you have to add these lines:

...
var drawMonth = $(this).data().datepicker.drawMonth; // <-- this is new

if (!date1 || date2) {
    $("#date-from").val(dateText);
    $("#date-to").val("");
    $(this).datepicker("option", "minDate", dateText);
} else {
    $("#date-to").val(dateText);
    $(this).datepicker("option", "minDate", null);
}

$(this).data().datepicker.drawMonth = drawMonth; // <-- this is new
$(this).datepicker("refresh"); // <-- this is new

This is not the most elegant solution, but unfortunately there is probably no option to control this behavior.

Upvotes: 1

Related Questions