I have a JS code in which when you change a field it calls a search routine. The problem is that I can't find any jQuery events that will fire when the Datepicker updates the input field.
For some reason, a change event is not called when Datepicker updates the field. When the calendar pops up it changes the focus so I can't use that either. Any ideas?
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="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 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="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>