jQuery Datepicker onchange event issue

You can use the datepicker’s onSelect event.

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

Live example:

$(".date")
.datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
    }
})
.on("change", function() {
    console.log("Got change event from field");
});
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type="text" class="date">
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://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 input for 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:

$(".date")
.datepicker({
    onSelect: function(dateText) {
        console.log("Selected date: " + dateText + "; input's current value: " + this.value);
        $(this).change();
    }
})
.on("change", function() {
    console.log("Got change event from field");
});
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type="text" class="date">
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

Leave a Comment