Friday, April 30, 2010

Cloning jQuery UI datepicker

In case you were having problems with cloning fields with jQuery UI datepicker attached to them - solutions mentioned in the interwebs are similar to this one:
$('.cloned-input').removeClass('hasDatepicker').datepicker(); 
However, that did not work for me. If you happen to have a set of similar symptoms:
  • new datepicker is not instantiated at all
  • JS errors occur while instantiating new datepicker
  • even if datepicker is cloned, it refers to the old field
the issue is that there are remaining (cloned) events (if you're using .clone(true) like me) on the field AND there is a still attached cloned datepicker object.

Solution

Either imitate datepicker('destroy') manually:
$input = $('.cloned-input'); 
// remove still present related DOM objects
$input.siblings('.ui-datepicker-trigger,.ui-datepicker-apply').remove();
// remove datepicker object and detach events 
$input
  .removeClass('hasDatepicker')
  .removeData('datepicker')
  .unbind()
  .datepicker();
or implement a different procedure:
  1. before cloning destroy the datepicker on the base input
  2. clone(true)
  3. recreate the datepicker on base input
  4. use unbind() and recreate datepicker on cloned input

2 comments:

Johan Guse said...

Many tks!

Vinay Umesh said...

Hi,
Can you please provide reference example so that I can better understand. I've use clone(true) and calendar is not working for cloned text fields.