This is definitely possible, and in my opinion not too much of an abuse of the datepicker widget. There is an option to initialize the widget in-line, which can be used for exactly the scenario you describe above.
There are a couple of steps you'll have to take:
Initialize the datepicker in-line. Attach the datepicker widget to a <div>
so that it will always appear and you won't have to attach it to an input
:
$("div").datepicker({...});
Tap into the beforeShowDay
event to highlight dates with specific events. Also, define your events in an array that you can populate and send down to the client:
Events array:
var events = [
{ Title: "Five K for charity", Date: new Date("02/13/2011") },
{ Title: "Dinner", Date: new Date("02/25/2011") },
{ Title: "Meeting with manager", Date: new Date("03/01/2011") }
];
Event handler:
beforeShowDay: function(date) {
var result = [true, '', null];
var matching = $.grep(events, function(event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
result = [true, 'highlight', null];
}
return result;
},
This might look a bit complex, but all it's doing is highlighting dates in the datepicker that have entries in the events
array defined above.
Define an onSelect
event handler where you can tell the datepicker what to do when a day is clicked:
onSelect: function(dateText) {
var date,
selectedDate = new Date(dateText),
i = 0,
event = null;
/* Determine if the user clicked an event: */
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
event = events[i];
}
i++;
}
if (event) {
/* If the event is defined, perform some action here; show a tooltip, navigate to a URL, etc. */
alert(event.Title);
}
}
Again, it looks like a lot of code, but all that's happening is that we're finding the event associated with the date clicked. After we find that event, you can take whatever action you want (show a tooltip, for example)
Here's a complete working example: http://jsfiddle.net/Zrz9t/1151/. Make sure to navigate to February/March to see the events.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…