Datepicker隐藏日历以显示月份和完整日历无法正常工作

时间:2014-07-15 07:45:08

标签: jquery calendar datepicker

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

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 Fiddle link

3 个答案:

答案 0 :(得分:2)

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

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

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

FIDDLE

答案 1 :(得分:1)

您还可以使用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');
    });
}

更新:上面的代码适用于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");
    });
}

答案 2 :(得分:1)

根据此answer,您需要将其隐藏在 beforeShow 而不是onChangeMonthYear中。首先,您需要定义一个新的CSS样式:

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

并在datepicker()函数的beforeShow事件中:

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