How Can I Use a Date Picker to Select a Whole Week?
October 7, 2012
It’s really unfortunate that this isn’t a default option, but what happens when you want to use a datepicker to select an entire week? This is useful for anything that requires a user to submit data in a week sensitive format, like timesheets or weekly event planning.
[cta id=’1682′]
This seems to have it down the best so far. Building off the original datepicker function in jQuery UI library, they were able to accomplish this task. Here’s the additional code:
$(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').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
$('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
});
$('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
** This can also be easily edited to work on input fields. Just replace the .ui-datepicker-calendar to #ui-datepicker-div in the mousemove and mouseleave functions. you would also need to add to following to the ‘onSelect’ function:
$('#weekSelect').val($.datepicker.formatDate( dateFormat, startDate, inst.settings )+"-"+$.datepicker.formatDate( dateFormat, endDate, inst.settings ))