Add legend to jQuery datepicker

2019-06-04 03:13发布

问题:

I am using a standard jQuery Datepicker and I need to modify it to display legend on the bottom. When I use beforeShow event, I cant append legend html to datepicker because there is no #ui-datepicker-div element, and datepicker does not supply afterShow event. This is my code:

var html = $('#datepickerLegendHolder').html();

$('#start_date.datepicker').datepicker({
        "dateFormat": 'yy-mm-dd', 
        minDate: 0, 
        showOn: "both",
        buttonImage: "/images/calendar-icon.png",
        maxDate: "+2Y",
        beforeShow: function(event, ui) { 
            $('#ui-datepicker-div').append(html);
        },
        onSelect: function (dateValue, inst) {
            $('#end_date.datepicker').datepicker("option", "minDate", dateValue);
            displayButtons();
        }
    });

Have anyone some alternative? Tnx

回答1:

At the time the onBeforeShow event is raised, the element #ui-datepicker-div does not exists yet.

A workaround is to use a setTimeout with a small duration (like 150ms) to append your legend to that element in the event handler. It could not be totally reliable although because of the architecture of the plugin, I don't know any other way.

Note: the documentation lists to a create event but the Datepicker does implement the Widget Factory so there is actually no create event raised !

$('#datepicker').datepicker({
    ...
    beforeShow: function(event, ui) { 
        setTimeout(function() {
            $('#ui-datepicker-div').append('lalala');
        }, 150);
    }
});​

DEMO