Search code examples
jquerytwitter-bootstrapbootstrap-datepicker

Bootstrap datepicker unexpectedly fires change event inside another event handler


I noticed unexpected event firing from Bootstrap datepicker. It only happens inside of another function/handler.

Normally setDate shouldn't trigger events and it doesn't! unless I wrap it into another function/handler.

Trying to understand the difference and get rid of unneeded event firing.

Please help.

//$('.set-date-button').click(function(event) {
  event.preventDefault();
  var startDate = '01/01/2017';
  $('.start .date').datepicker('setDate', startDate);
//}); When commented, change event doesn't fire, when uncommented - unexpected change event fires.

https://jsfiddle.net/xek22wpq/

Using change or changeDate doesn't make any difference.

$('.set-date-button').click(function(event) {
  event.preventDefault();
  var startDate = '01/01/2017';
  $('.start .date').datepicker('setDate', startDate);
});

$(document).on('change', '.start .date', function() {
  alert('fired!');
});
<link href="https://rawgit.com/uxsolutions/bootstrap-datepicker/master/dist/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://rawgit.com/uxsolutions/bootstrap-datepicker/master/dist/js/bootstrap-datepicker.min.js"></script>
<button class='set-date-button'>Set Date</button>
<div class='start'>
  <input class='date' placeholder='mm/dd/yyyy'>
</div>


Solution

  • https://github.com/uxsolutions/bootstrap-datepicker/issues/575

    I found that update method doesn't trigger changeDate, but triggers change. And this is how I eliminated this extra firing:

    $('.set-date-button').click(function(event) {
      event.preventDefault();
      var startDate = '01/01/2017';
      $('.start .date').datepicker('update', startDate);
    });
    
    $(document).on('changeDate', '.start .date', function() {
      alert('fired!');
    });
    

    https://jsfiddle.net/xek22wpq/10/