zbestzeus zbestzeus - 5 months ago 414
jQuery Question

JQuery Datepicker onchange event help!

I have JS code that when you change a field it will call a search routine.... the problem is I can't find a Jquery event that will fire when the Datepicker updates the input field.

For some reason a change event isn't called when datepicker updates the field. When the calendar pops up it changes the focus so I can't use that either. Any ideas?

Answer

You can use the datepicker's onSelect event.

$(".date").datepicker({
  onSelect: function(dateText) {
    display("Selected date: " + dateText + "; input's current value: " + this.value);
  }
});

Live example:

jQuery(function($) {

  $(".date").datepicker({
    onSelect: function(dateText) {
      display("Selected date: " + dateText + "; input's current value: " + this.value);
    }
  }).on("change", function() {
    display("Got change event from field");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

});
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

Unfortunately, onSelect fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires onSelect (even if nothing changed), and doesn't fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual change event, or possibly a datepicker-specific one).


If you like, of course, you can make the change event on the input fire:

$(".date").datepicker({
  onSelect: function() {
    $(this).change();
  }
});

That will fire change on the underlying inputfor any handler hooked up via jQuery. But again, it always fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via data) and compare.

Live example:

jQuery(function($) {

  $(".date").datepicker({
    onSelect: function(dateText) {
      display("Selected date: " + dateText + "; input's current value: " + this.value);
      $(this).change();
    }
  }).on("change", function() {
    display("Got change event from field");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

});
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date'>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

Comments