82

I have an input element with an attached datepicker created using bootstrap-datepicker.

<div class="well">
    <div class="input-append date" id="dp3" data-date="2012-01-02" data-date-format="yyyy-mm-dd">
        <input type="text" id="date-daily">
        <span class="add-on"><i class="icon-th"></i></span>    
    </div>
</div>

<script language="JavaScript" type="text/javascript">
    $(document).ready(function() {
        $('#dp3').datepicker();
        $('#date-daily').val('0000-00-00');
        $('#date-daily').change(function () {
            console.log($('#date-daily').val());
        });
    });
</script>

When the user changes the date by typing directly into the input element, I can get the value with the input element's onChange event, as shown above. But when the user changes the date from datepicker (i.e. by clicking a date on the calendar), the onChange handler is not called.

How can I detect changes to the selected date that are made via the datepicker, rather than by typing into the input element?

Haseeb Ibrar
  • 337
  • 5
  • 18
user2269756
  • 937
  • 1
  • 10
  • 18

8 Answers8

152

All others answers are related to jQuery UI datepicker, but the question is about bootstrap-datepicker.

You can use the on changeDate event to trigger a change event on the related input, and then handle both ways of changing the date from the onChange handler:

changeDate

Fired when the date is changed.

Example:

$('#dp3').datepicker().on('changeDate', function (ev) {
    $('#date-daily').change();
});
$('#date-daily').val('0000-00-00');
$('#date-daily').change(function () {
    console.log($('#date-daily').val());
});

Here is a working fiddle: http://jsfiddle.net/IrvinDominin/frjhgpn8/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
  • There's also a `clearDate` event you should listen to, if your date is nullable. However, this event does not seem to trigger when clearing through the context menu (in Chrome). – Rudey Sep 24 '14 at 13:21
  • Is it possible to fire the event after changing input value via code? – Musaddiq Khan Aug 25 '17 at 13:08
  • The fiddle no longer works because of external resources. Updated version here: http://jsfiddle.net/jsrq4ot0/2/ – Yogi Dec 06 '17 at 23:32
  • 1
    for bootstrap-datetimepicker the event-name is dp.change – phil May 04 '18 at 09:30
  • See bootstrap-datepicker events documentation https://bootstrap-datepicker.readthedocs.io/en/latest/events.html – chri3g91 Sep 02 '20 at 07:13
40

Try this:

$("#dp3").on("dp.change", function(e) {
    alert('hey');
});
Petr
  • 1,193
  • 1
  • 15
  • 27
16

Here is my code for that:

$('#date-daily').datepicker().on('changeDate', function(e) {
    //$('#other-input').val(e.format(0,"dd/mm/yyyy"));
    //alert(e.date);
    //alert(e.format(0,"dd/mm/yyyy"));
    //console.log(e.date); 
});

Just uncomment the one you prefer. The first option changes the value of other input element. The second one alerts the date with datepicker default format. The third one alerts the date with your own custom format. The last option outputs to log (default format date).

It's your choice to use the e.date , e.dates (for múltiple date input) or e.format(...).

here some more info

Lucio Chávez
  • 161
  • 1
  • 3
14

$(function() {
  $('input[name="datetimepicker"]').datetimepicker({
    defaultDate: new Date()
  }).on('dp.change',function(event){
    $('#newDateSpan').html("New Date: " + event.date.format('lll'));
    $('#oldDateSpan').html("Old Date: " + event.oldDate.format('lll'));
  });
  
});
<link href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script src="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>

<div class="container">
  <div class="col-xs-12">
    <input name="datetimepicker" />
    <p><span id="newDateSpan"></span><br><span id="oldDateSpan"></span></p>
  </div>
</div>
crashtestxxx
  • 1,405
  • 5
  • 21
  • 30
  • 1
    Please [edit] with more information. Code-only and "try this" answers are [discouraged](//meta.stackexchange.com/questions/196187), because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – Mogsdad May 06 '16 at 22:06
  • This works well if you have set the current date to the text box. If you had set the current date then dp.onchange wil trigger while the page loads. – Deepesh Thapa Jan 22 '21 at 11:29
4

Try with below code sample.it is working for me

var date_input_field = $('input[name="date"]');
    date_input_field .datepicker({
        dateFormat: '/dd/mm/yyyy',
        container: container,
        todayHighlight: true,
        autoclose: true,
    }).on('change', function(selected){
        alert("startDate..."+selected.timeStamp);
    });
Yogesh
  • 715
  • 1
  • 7
  • 20
3
$(document).ready(function(){

$("#dateFrom").datepicker({
    todayBtn:  1,
    autoclose: true,
}).on('changeDate', function (selected) {
    var minDate = new Date(selected.date.valueOf());
    $('#dateTo').datepicker('setStartDate', minDate);
});

$("#dateTo").datepicker({
    todayBtn:  1,
    autoclose: true,}) ;

});
Sinto
  • 3,915
  • 11
  • 36
  • 70
1

Based on Irvin Dominin example, I've created 2 examples supporting Paste and hit Enter.

This works in Chrome: http://jsfiddle.net/lhernand/0a8woLev/

$(document).ready(function() {
   $('#date-daily').datepicker({
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    })
    /* On 'paste' -> loses focus, hide calendar and trigger 'change' */
    .on('paste', function(e) {
      $(this).blur();
      $('#date-daily').datepicker('hide');
    })
    /* On 'enter' keypress -> loses focus and trigger 'change' */
    .on('keydown', function(e) {

      if (e.which === 13) {
         console.log('enter');
         $(this).blur();
      }
    })
    .change(function(e) {
      console.log('change');
      $('#stdout').append($('#date-daily').val() + ' change\n');
    });
});

But not in IE, so I created another example for IE11: https://jsbin.com/timarum/14/edit?html,js,console,output

$(document).ready(function() {
   $('#date-daily').datepicker({
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    })
    // OnEnter -> lose focus
    .on('keydown', function(e) {
         if (e.which === 13){ 
           $(this).blur();
         }
    })
    // onPaste -> hide and lose focus
    .on('keyup', function(e) {
         if (e.which === 86){ 
            $(this).blur();
            $(this).datepicker('hide');
          }
    })
    .change(function(e) {
       $('#stdout').append($('#date-daily').val() + ' change\n');
    });
});

If last example still doesn't work in IE11, you can try splitting the setup:

// DatePicker setup
$('.datepicker').datepicker({
    format: 'dd/mm/yyyy',
    assumeNearbyYear: true,      /* manually-entered dates with two-digit years, such as '5/1/15', will be parsed as '2015', not '15' */
    autoclose: true,             /* close the datepicker immediately when a date is selected */
    orientation: 'bottom rigth',
    todayHighlight: true,        /* today appears with a blue box */
    keyboardNavigation: false    /* select date only onClick. when true, is too difficult free typing  */
}); 

And the event handlers: (note I'm not using $('.datepicker').datepicker({)

   // Smoker DataPicker behaviour
    $('#inputStoppedDate')
    // OnEnter -> lose focus
    .on('keydown', function (e) {
        if (e.which === 13){ 
            $(this).blur();
        }
    })
    // onPaste -> hide and lose focus
    .on('keyup', function (e) {
        if (e.which === 86){ 
            $(this).blur();
            $(this).datepicker('hide');
        }
    })
    .change(function (e) {
        // do saomething
    });
Luis Hernandez
  • 453
  • 5
  • 8
-17

You can use onSelect event

 $("#date-daily").datepicker({
  onSelect: function(dateText) {
   alert($('#dp3').val());
  }
});

It is Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.

SEE HERE

PSR
  • 39,804
  • 41
  • 111
  • 151
  • 2
    You're answer describes how to solve the issue in jquery datepicker, however OP was asking about bootstrap-datepicker which is a different component (though designed for the same purpose). In other words, you're answer is wrong. – jahu May 15 '14 at 09:02
  • this is not the right datepicker mentioned, mark's answer is correct – Caner May 29 '14 at 18:34