Joining a Blur JQuery Datepicker Event

I am working on a jQuery plugin for use with text fields, and I would like it to work with jQueryUI widgets that use text fields such as datepicker. This causes me problems, because it seems that the blur event on the datepicker is selected before the value is actually set.

The workaround I used was to set a timeout before executing my code to set the time for the datepickers value. See below code:

$(this).blur(function() { // $(this).val() == "" var elem = $(this); setTimeout(function() { //elem.val() != "" },100); }); 

I am not sure if this solution 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, this will not work - I worry if the code is slow to execute for some reason 100 may not always be enough.

Can anyone think of a better solution to this problem?

+6
source share
3 answers

In the end, my solution was to dynamically connect to the onClose event if the text field in question is used by the dumper (by checking the hasDatepicker class). The problem is that you cannot bind to an event, as usual, since a datepicker can only have one function attached to it by specific events. To get around this, I check if there is already a connected function, 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); } 
+6
source

There are several events in datepicker that you could associate with onSelect or onClose and this inside them is an input that is a date selector. You can use datepicker ui argument to get value also

 $(selector).datepicker({ onClose:function(evt, ui){ $(this).myPlugin('someMethod'); }) }) 
+5
source

This is an easier way to do this:

 $('#element').datepicker({ onClose: function() { $(this).trigger('change'); } }); $('#element').bind('change',function(){ // someFunction(); }); 
0
source

All Articles