I have a datepicker which is set up to select a whole week. I have two buttons which are supposed to move the selected dates forward and backward a week. The forward button works all the time, but the backward button only works if the month changes. If the month does not change nothing happens. The code is below.
$(document).ready(function() {
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function() {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')}, 1);
}
$('.week-picker').datepicker({
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('.startDate').val($.datepicker.formatDate(dateFormat, startDate, inst.settings));
$('.endDate').val($.datepicker.formatDate(dateFormat, endDate, inst.settings));
$('.week-picker').val(" " + $.datepicker.formatDate(dateFormat, startDate, inst.settings) + " - " + $.datepicker.formatDate(dateFormat, endDate, inst.settings));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if (date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker').datepicker("setDate", new Date());
$('.ui-datepicker-current-day').click();
$('.week-picker .ui-datepicker-calendar tr').on('mousemove', null, function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').on('mouseleave', null, function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
$('#preWeek').click(function () {
var startDate = $('.startDate').val();
var newDate = new Date(startDate);
newDate.setDate(newDate.getDate() - 7);
$('.week-picker').datepicker("setDate", new Date(newDate));
$('.ui-datepicker-current-day').click();
return false;
});
$('#nextWeek').click(function () {
var endDate = $('.endDate').val();
var newDate = new Date(endDate);
newDate.setDate(newDate.getDate() + 1);
$('.week-picker').datepicker("setDate", new Date(newDate));
$('.ui-datepicker-current-day').click();
return false;
});
});
I cannot figure out why the date will not move backwards except when the month changes.
Here is the fiddle: Click Here