日期picker隐藏日历显示月-年和完整的日历不能正常工作



我的表单中有两个字段,一个显示日期选择器,只显示月份和年份,另一个显示完整的日历。

From <input type="text" name="startdate" id="datepicker"/>
To <input type="text" name="enddate" id="datepicker1"/>

javascript是:

$('#datepicker').datepicker( {
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'mm-yy',
    onChangeMonthYear: function(year, month, widget) {
        $('.ui-datepicker-calendar').hide();
    },
    onClose: function(dateText, inst) { 
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
    },
}).click(function(){
    $('.ui-datepicker-calendar').hide();
});
$('#datepicker1').datepicker( {
    changeMonth: true,
    changeYear: true, 
    dateFormat: 'dd/mm/yy',
}).click(function(){
    $('.ui-datepicker-calendar').show();
});

到目前为止,这两个日历工作良好。但是当我们更改第一个日历的月份或年份时,将显示完整的日历!我试着在onChangeMonthYear中添加隐藏日历,但不工作!

JS提琴链接

你正在做的是一个hack,你试图隐藏日历部分时,一个月或年显示,但自定义onChangeMonthYear事件触发之前,日期选择器显示。

为了进一步破解它,您可以使用超时来延迟

    onChangeMonthYear: function(year, month, widget) {
        setTimeout(function() {
           $('.ui-datepicker-calendar').hide();
        });
    },

小提琴

您还可以使用css隐藏日历表。这个解决方案不会像setTimeout解决方案那样导致闪烁。

.ui-datepicker-calendar {
    display: none !important;
}

如果你想要显示另一个带有日历表的DatePicker,请在其上添加一个click事件并设置其onChangeMonthYear事件。

$(".class").click(function () {
    // eq = 2 if you already have 2 DatePickers
    $("table.ui-datepicker-calendar").eq(2).prop('style', 'display: block !important');
});
onChangeMonthYear: function (year, month, inst) {
    setTimeout(function() {
        $(inst.dpDiv).find("table.ui-datepicker-calendar").prop('style', 'display: block !important');
    });
}

UPDATE:上面的代码适用于Firefox,但不适用于Chrome和IE。
此代码适用于Firefox, Chrome和IE:

$(".class").click(function () {
    // eq = 2 if you already have 2 DatePickers
    $("table.ui-datepicker-calendar").eq(2).removeClass("ui-datepicker-calendar");
});
onChangeMonthYear: function (year, month, inst) {
    setTimeout(function() {
        $(inst.dpDiv).find("table.ui-datepicker-calendar").removeClass("ui-datepicker-calendar");
    });
}

根据这个答案,你需要隐藏它在beforeShow而不是onChangeMonthYear。首先,你需要定义一个新的css样式:

.hide-calendar .ui-datepicker-calendar {
    display: none;
}

和datepicker()函数中的beforeShow事件

beforeShow: function(input, inst) {
     $('#ui-datepicker-div').addClass('hide-calendar');
}

最新更新