I need to show custom text on some dates at Jquery UI datepicker, to be more precise, to render a specific price for some dates. My idea was to use beforeShowDa
Based on @PrestonS's answer and this post, I have a nice simple solution that doesn't need to add tags to header.
My solution updates Preston's as such:
ModifiedupdateDatePickerCells function:
function updateDatePickerCells(dp) {
/* Wait until current callstack is finished so the datepicker
is fully rendered before attempting to modify contents */
setTimeout(function () {
//Fill this with the data you want to insert (I use and AJAX request). Key is day of month
//NOTE* watch out for CSS special characters in the value
var cellContents = {1: '20', 15: '60', 28: '100'};
//Select disabled days (span) for proper indexing but apply the rule only to enabled days(a)
$('.ui-datepicker td > *').each(function (idx, elem) {
var value = cellContents[idx + 1] || 0;
/***** MAGIC! *****/
$(this).attr('data-content', value);
// and that's it! (oh, so easy)
});
}, 0);
}
With this solution, you don't need the addCSSRule function at all.
Modified css:
/* to target all date cells */
.ui-datepicker td > *:after {
content: attr(data-content); /***** MAGIC! *****/
/* add your other styles here */
}
/* to target only allowed date cells */
.ui-datepicker td > a:after {
}
/* to target only disabled date cells */
.ui-datepicker td > span:after {
}
Initializing with the datepicker object
If you need the datepicker object in the updateDatePickerCells function, here is a way to get it at initialization time. (Based on this post)
var calendarElem = $('#DatePicker').datepicker({
changeMonth: true,
changeYear: true,
minDate: 0,
//The calendar is recreated OnSelect for inline calendar
onSelect: function (date, dp) {
updateDatePickerCells( dp );
},
onChangeMonthYear: function(month, year, dp) {
updateDatePickerCells( dp );
},
beforeShow: function(elem, dp) { //This is for non-inline datepicker
updateDatePickerCells( dp );
}
});
var datepicker = $.datepicker._getInst(calendarElem[0]);
updateDatePickerCells(datepicker);