jQuery Datepicker onSelect event get class

你离开我真会死。 提交于 2019-12-12 06:09:57

问题


I'm trying to get the class set in the beforeShowDay function of a jQuery datepicker when a user clicks on the date. Something like this:

$("#calendar").datepicker({
    minDate: today,
    dateFormat: dateformat,
    beforeShowDay: function(date) {         
        // set all the dates to have reserved class for now 
        return [true, 'reserved', 'this date reserved'];
    },
    onSelect: function(date, el){
        if ($(el).hasClass('reserved')){
            // on click, check if reserved class exists. 
            console.log('it is reserved!');
        } else {
            console.log('it is not reserved');
        }
    }
});

Every click returns "not reserved". How can I check the class of the clicked element?

http://jsfiddle.net/sf90zw72/


回答1:


Unfortunately it's a lot harder than that, the el argument you're getting is an object containg the datePicker instance, not the element clicked, from the documentation

...receives the selected date as text and the datepicker instance as parameters.

Only the date selected and the parent Datepicker element is included in that object, so you have to use those properties to select the element and check for the class.

Note that in your example all dates will have the class reserved as there's no condition, but I'm assuming that's different in the actual code

(function ($) {
    $(document).ready(function () {
        $("#calendar").datepicker({
            dateFormat: 'yyyy-mm-dd',
            beforeShowDay: function (date) {
                return [true, 'reserved', 'this date reserved'];
            },
            onSelect: function (date, el) {
                var day  = el.selectedDay,
                    mon  = el.selectedMonth,
                    year = el.selectedYear;

                var el = $(el.dpDiv).find('[data-year="'+year+'"][data-month="'+mon+'"]').filter(function() {
                    return $(this).find('a').text().trim() == day;
                });

                if ( el.hasClass('reserved')){
                    console.log('it is reserved!');
                } else {
                    console.log('it is not reserved');
                }
            }
        });
    });
})(jQuery);

FIDDLE




回答2:


I think it can be as simple as this:

    $jx('.date-picker').datepicker({
        onSelect: function(dateText, $el) {
            if ($jx(this).hasClass('start-date')) {
                console.log('...');
            }
        }           
    });


来源:https://stackoverflow.com/questions/28889828/jquery-datepicker-onselect-event-get-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!