I'm working on a jQuery plugin for use with textboxes and I would like it to work with jQueryUI widgets that make use of textboxes, such as the datepicker. This is causing me problems because it seems that the blur event on the datepicker is thrown before the value is actually set.
A workaround I have used is to set a timeout before executing my code to allow time for the datepickers value to be set. See below code:
$(this).blur(function() {
// $(this).val() == ""
var elem = $(this);
setTimeout(function() {
//elem.val() != ""
},100);
});
I am not sure this workaround is the best solution to the problem or even if it will always work. If I set the timeout to 10 milliseconds instead of 100, it does not work - I'm worried if code is slow to execute for whatever reason 100 may not always be enough.
Can anyone think of a better solution to this problem?
In the end my solution was to dynamically hook in to the onClose
event if the textbox in question is used by a datepicker (by checking for the hasDatepicker
class). The problem with this is that you cannot bind to the event as you normally would as the datepicker can only have one function attached to it's specific events. To get around this I check if there is a function already attached, and if so call it after my code:
var elem = $(this);
var someFunction = function() {
//elem.val() != ""
}
if (elem.hasClass('hasDatepicker')) {
var onClose = elem.datepicker('option','onClose');
elem.datepicker('option','onClose', function() {
someFunction();
if (onClose) { onClose(elem.val()); }
});
} else {
elem.bind('blur',someFunction);
}