I have a div in which there is a datepicker. I use something like this to clone it:
mydiv = $('#someDiv');
// works fine so far
mydiv.find('input.datefield').datepicker();
// clone without the events and insert
newDiv = myDiv.clone(false).insertAfter(myDiv);
// datepicker won't re-init if this class is present
newDiv.find('.hadDatepicker').removeClass('hadDatepicker');
// reinitialize datepicker
newDiv.find('input.datefield').datepicker();
This is a stripped down version of my code. It works and the calendar shows up as expected where it is expected .. but when a date is clicked, the previous datepicker’s value gets updated.. (the one from which it was cloned).
I’ve tried to destroy the (inexisting) instance before like this:
newDiv.find('input.datefield').datepicker('destroy').datepicker();
No luck ..
I’ve checked how it keeps track of instances and manually cleared the data like this:
newDiv.find('input.datefield').data('datepicker', false).datepicker('destroy').datepicker();
Still no luck.
What I don’t understand is that only the date selection behavior is buggy, everything else works as expected.
I really don’t know what else to check now ..
Here’s the problem. datepicker creates UUID-based ID attributes for the input fields it binds when you initialize it. You cloning those elements results in more elements with either the same ID (which jQuery does not like) or a different ID if your clone routine manages that (which means datepicker does not know about the clones). In other words, datepicker only initializes all the elements matching your selector at the time you call it. it actually makes less sense to try to destroy/disable/enable over and over, when you can just wrap the init call inside whatever function you use to create the clones.
Because my clone functions typically copy from hidden DOM elements rather than visible ones, I have the luxury deciding whether I need to bind before or after cloning. So, make #templateDiv a hidden element on your page with the INPUT element already in there.
and that pretty much does it. Clone(true) whenever you can, it’ll save you headaches in the long run.