问题
I am following this jsFiddle to be able to highlight and select whole week from datepicker.
I have customized it to work with jQuery 1.9 by changing .live() to .on(). Here is the edited jsFiddle. It works fine but in its current state the week is only highlighted once the user click on a date.
What I want to achieve is to highlight (and populate dates in startDate and endDate vars) the week to which current date belongs automatically on startup without clicking current date. I have tried the following but it doesn't seem to work
var currentDate = $(".week-picker").datepicker("getDate");
var onSelectFunction = $(".week-picker").datepicker("option","onSelect");
var format = $(".week-picker").datepicker( "option", "dateFormat" );
var currDate = $.datepicker.formatDate(format,currentDate)
onSelectFunction( currDate );
Any Suggestions?
回答1:
Try this
$(function () {
var startDate;
var endDate;
var selectCurrentWeek = function () {
window.setTimeout(function () {
$('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
var $weekPicker = $('.week-picker');
function updateWeekStartEnd() {
var date = $weekPicker.datepicker('getDate') || new Date();
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
}
updateWeekStartEnd();
function updateDateText(inst) {
var dateFormat = inst != 'start' && inst.settings.dateFormat ? inst.settings.dateFormat : $.datepicker._defaults.dateFormat;
console.log( dateFormat)
$('#startDate').text($.datepicker.formatDate(dateFormat, startDate, inst.settings));
$('#endDate').text($.datepicker.formatDate(dateFormat, endDate, inst.settings));
}
updateDateText('start');
$weekPicker.datepicker({
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function (dateText, inst) {
updateWeekStartEnd();
updateDateText(inst);
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();
}
});
selectCurrentWeek();
$('.week-picker .ui-datepicker-calendar tr').on('mousemove', function () {
$(this).find('td a').addClass('ui-state-hover');
});
$('.week-picker .ui-datepicker-calendar tr').on('mouseleave', function () {
$(this).find('td a').removeClass('ui-state-hover');
});
});
DEMO: http://jsfiddle.net/eFzG4/
回答2:
you can also trigger click on the current day
$(".ui-datepicker-current-day").click();
来源:https://stackoverflow.com/questions/14673277/highlight-current-week-when-datepicker-is-loaded