JQuery UI datepicker IE focus fix
The jquery ui datepicker control is quite slick and easy to use, and as you see here it can be customized through various events.
At my current client we have multiple controls on the page that listen for onblur and onchange events to notify of changes to the page (most notably an html5 placeholder enabler). But the datepicker does not send the blur event when a selection happens. Also, our users wanted focus to return the text input field after the date selection. So we need to setup some event handlers to call the blur and focus events upon date selection.
First let’s start with a simple datepicker that is applied to any input field having css class dateInput, with a few extra options:
$("input.dateInput").datepicker({ changeMonth: true, changeYear: true, showAnim: "fadeIn", yearRange: 'c-30:c+30', showButtonPanel: true });
Adding a blur and change event on datepicker selection is rather easy:
$("input.dateInput").datepicker({ changeMonth: true, changeYear: true, showAnim: "fadeIn", yearRange: 'c-30:c+30', showButtonPanel: true,/* blur needed to correctly handle placeholder text */ onSelect: function(dateText, inst) { $(this).blur().change(); } });
But adding focus is a little more difficult because of a difference in browser behavior. Simply adding a .focus() to onSelect and onClose will suffice for Chrome and Firefox but IE will reopen the datepicker once it receives the focus. In order to handle IE we can simply implement the beforeShow event handler, returning false when we reach a case where IE should not reopen the datepicker window. I’ve added a fixFocusIE variable to track this:
Hopefully this helps someone else searching for a way to focus on the original input field after selecting a date with the JQuery UI Datepicker control.
Note: A little writeup cross-posted on the OPI blog about making the jquery UI datepicker send blur events when dates change, while handling a quirk with IE:
http://www.objectpartners.com/2012/06/18/jquery-ui-datepicker-ie-focus-fix/