Search code examples
twitter-bootstrapbootstrap-datetimepickereonasdan-datetimepicker

How to autoclose datetimepicker of Bootstrap using dp.change event?


How to autoclose a datetimepicker on date select only. I am using the dp.change event but it closes the datetimepicker even on changing the time.

$('.datetimepicker').each(function () {
    $(this).on('dp.change', function (ev) {

       $(this).data('DateTimePicker').hide();

    });
});

What will be the className for the timePicker? What if I get the class and tell datetimepicker not to close if the className is equal to the className of timepicker?

And what is the latest version for the datetimepicker?

1 is the this: http://eonasdan.github.io/bootstrap-datetimepicker/

2nd is this with autoClose property.

http://www.malot.fr/bootstrap-datetimepicker/

Thanks.


Solution

  • Using eonasdan datetimepicker you can check if the new selected date is the same of the previous selected date (using moment isSame).

    Note the dp.change receives oldDate and date as parameter.

    Here a working example:

    $('.datetimepicker').datetimepicker().on('dp.change', function(e){
      if( !e.oldDate || !e.date.isSame(e.oldDate, 'day')){
        $(this).data('DateTimePicker').hide();
      }
    });
    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>
    <link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.42/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/locale/en-gb.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.42/js/bootstrap-datetimepicker.min.js"></script>
    
    <div class="input-group date datetimepicker">
      <input type="text" class="form-control" />
      <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
      </span>
    </div>