I am using jQuery UI datepicker and I want to display additional text inside date cells next to the date. This is the desired behavior:
Unfortunately, manipulating date cells using .text()
and .html()
functions breaks the datepicker functionality. See following demo and try to use the datepicker. Notice that when you select a date (i) the custom text is gone (ii) changing months destroys the calendar and lands you on "undefined NaN" month:
https://jsfiddle.net/salman/aLdx4L0y/
Is there a solution?
Well, you can monkey-patch jQuery UI and risk breaking the code with newer versions or you can use documented callbacks to add custom data-*
attributes to datepicker and display them using CSS pseudo elements:
$(function() {
$("#datepicker").datepicker({
beforeShow: addCustomInformation,
//---^----------- if closed by default (when you're using <input>)
beforeShowDay: function(date) {
return [true, date.getDay() === 5 || date.getDay() === 6 ? "weekend" : "weekday"];
},
onChangeMonthYear: addCustomInformation,
onSelect: addCustomInformation
});
addCustomInformation(); // if open by default (when you're using <div>)
});
function addCustomInformation() {
setTimeout(function() {
$(".ui-datepicker-calendar td").filter(function() {
var date = $(this).text();
return /\d/.test(date);
}).find("a").attr('data-custom', 110); // Add custom data here
}, 0)
}
.ui-datepicker .weekend .ui-state-default {
background: #FEA;
}
.ui-datepicker-calendar td a[data-custom] {
position: relative;
padding-bottom: 10px;
}
.ui-datepicker-calendar td a[data-custom]::after {
/*STYLE THE CUSTOME DATA HERE*/
content: '$' attr(data-custom);
display: block;
font-size: small;
}
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="//code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id="datepicker">
Here's an updated JSFiddle
Side note: I'm not sure which functionality is broke in your demo, but since this solution is using documented callbacks and CSS, I believe it's less likely to break anything in future than monkey patching