3

我有一个包含多个日期时间选择器的 html 模板。如果我单击按钮打开一个日期时间选择器,然后单击另一个打开新的,第一个保持不变(它不会关闭)。我希望一次只能打开一个日期时间选择器。

这是一个JsFiddle 演示

$('#datetimepicker1, #datetimepicker2').datetimepicker();

这是 bootstrap datetimepicker 2.5 在使用 moment 2.5(moment-with-langs)时的标准行为,但现在它似乎不是那样工作的。

有没有人有任何想法来解决这个问题?

注意:我使用 Eonasdan bootstrap-datetimepicker 版本 3.0.3 和 moment 2.8 (moment-with-locales)、jQuery 1.9 和 Bootstrap 3

这里棘手的是 bootstrap-datetimepicker 附加到每个与触发按钮完全无关的初始化的 datetimepicker 上<body><div>

4

2 回答 2

5

尝试这个:

$('.date').datetimepicker();
$(document).ready(function() {
    // Select all elements with the 'date' class
    $('.date').on('dp.show', function() {
        $('.date').not($(this)).each(function() {
            $(this).data("DateTimePicker").hide();
            // $('.date').not($(this)) selects all the .date elements except
            // for the one being shown by the datetimepicker dp.show event.
            // The dp.show event is fired when a new datetimepicker is opened.
            // We use the .data("DateTimePicker") to access the datetimepicker object
            // (we have to use a jQuery each loop in order to access all the 
            // datetimepickers.
            // .hide() -- we hide it.
        });
    });
});

这应该只允许一次打开一个日期时间选择器。

于 2014-09-22T17:14:57.750 回答
1

尽管 Joel Lubrano 的答案适用于预加载的小部件......但它缺乏使用动态生成的小部件(通过 JS)的可能性。同时,我设法从组件内部解决了这个问题,通过添加一行来解决这两个问题。

在组件的 JS 中定位picker.show函数(根据版本(v1.3.1 中的 this),在第 1150 行附近)...在该函数的最后一个 else 语句中,将以下行作为该语句的第一条指令。

$('.picker-open').hide().removeClass('picker-open');

就是这样。之后,您只需将 DTP 初始化封装在一个函数中,并在文档准备好和动态生成的小部件之后调用它。

function DTPinit(){
    $('.dtp').datetimepicker();
}

$(function(){
    DTPinit();
    $('#dtp_gen').on('click', function(){
        $('body').append('<div class="form-group"><div class="input-group dtp date""><input type="text" class="form-control datetimepicker" /><span class="input-group-addon"><span class="glyphicon-calendar glyphicon"></span></span></div></div>');
        DTPinit();
    });
});

在这里,您有一个JSFiddle演示了我上面所描述的内容。BS-DTP 组件正在 fiddle JS 容器中加载以进行编辑。

于 2014-10-03T09:40:50.040 回答