[jquery] Detect change to selected date with bootstrap-datepicker

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?

The answer is


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


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

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

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


Try this:

$("#dp3").on("dp.change", function(e) {
    alert('hey');
});

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

});

_x000D_
_x000D_
$(function() {_x000D_
  $('input[name="datetimepicker"]').datetimepicker({_x000D_
    defaultDate: new Date()_x000D_
  }).on('dp.change',function(event){_x000D_
    $('#newDateSpan').html("New Date: " + event.date.format('lll'));_x000D_
    $('#oldDateSpan').html("Old Date: " + event.oldDate.format('lll'));_x000D_
  });_x000D_
  _x000D_
});
_x000D_
<link href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" rel="stylesheet"/>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://momentjs.com/downloads/moment.min.js"></script>_x000D_
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>_x000D_
<script src="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="col-xs-12">_x000D_
    <input name="datetimepicker" />_x000D_
    <p><span id="newDateSpan"></span><br><span id="oldDateSpan"></span></p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to datepicker

Angular-Material DateTime Picker Component? $(...).datepicker is not a function - JQuery - Bootstrap Uncaught TypeError: $(...).datepicker is not a function(anonymous function) Get date from input form within PHP Angular bootstrap datepicker date format does not format ng-model value jQuery Datepicker close datepicker after selected date bootstrap datepicker setDate format dd/mm/yyyy bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date Clear the value of bootstrap-datepicker Disable future dates after today in Jquery Ui Datepicker

Examples related to bootstrap-datepicker

bootstrap datepicker setDate format dd/mm/yyyy bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date How do I get bootstrap-datepicker to work with Bootstrap 3? Detect change to selected date with bootstrap-datepicker Bootstrap datepicker disabling past dates without current date bootstrap datepicker today as default Bootstrap DatePicker, how to set the start date for tomorrow? How to restrict the selectable date ranges in Bootstrap Datepicker? Twitter Bootstrap date picker