Search code examples
javascriptjquerytwitter-bootstrapdatetimepickerbootstrap-datetimepicker

Bootstrap DateTimePicker: Open one datetimepicker at a time


I have an html template with more than one datetimepickers. If I click in the button to open one datetimepicker and after that click in another to open the new one, the first one stays unchanged (it doesn't close). I want to be able to open only one datetimepicker at a time.

Here's a JsFiddle Demo

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

This was standard behaviour for bootstrap datetimepicker 2.5 when working with the moment 2.5 (moment-with-langs) but now it seems not to be working like that.

Does anyone have any ideas to workaround this issue?

Note: I'm using Eonasdan bootstrap-datetimepicker version 3.0.3 with moment 2.8 (moment-with-locales), jQuery 1.9 and Bootstrap 3

What's tricky here is that bootstrap-datetimepicker appends to <body> a <div> for each datetimepicker initialized that is completely unrelated to its trigger button.


Solution

  • Although Joel Lubrano's answer works as intended for preloaded widgets ... it lacks the possibility to work with dynamically generated ones (via JS). Meanwhile, I've managed to work around this issue from inside the component solving both problems by adding one single line.

    Inside the component's JS locate the picker.show function (around line 1150 depending on version (this in v1.3.1)) ... inside the last else statement of that function, place the following line as the first instruction of that statement.

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

    and that's it. After that you only need to encapsulate the DTP initialization inside a function and call it on document ready and after dynamically generated widgets.

    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();
        });
    });
    

    Here you have a JSFiddle demonstating what I'm describing above. The BS-DTP component is being loaded inside the fiddle JS container for editing purposes.