Friday, April 20, 2012

Moving a jQuery Date Picker

In case you haven't noticed by this point, I am a jQuery fan. It makes working with javascript about a million times easier. Every once in a while, I stumble upon a little quirk, though, that ends up sinking hours of time trying to track down. This is one of those quirks.

I needed to make use of the jQuery UI Date Picker feature. Lovely little tool for dropping in an easy date picker. However, I was also doing some other jQuery magic with it - the date picker was in a form that could be used to edit multiple different instances on the page. I had it start out as hidden, then move it to the appropriate location and show it. Here is the code:
function moveEditForm(newLocation) {
    $('#my-edit-form').remove().insertAfter(newLocation).show();
}

There was one problem - the date picker, which I initialized on page load, would no longer open up the calendar. Took me forever to figure out why, as there was no javascript errors, nothing at all to indicate a problem. As it turns out, if you remove an initialized date picker from the page, and then add it back in somewhere else, the date picker functionality gets all foobarred.

With a little experimentation, I found that what I had to do was destroy the date picker before removing it from the page, then re-init it after I inserted it back in. The updated code looked more like this:
function moveEditForm(newLocation) {
    $( "#my-datepicker" ).datepicker("destroy");
    $('#my-edit-form').remove().insertAfter(newLocation).show();
    $( "#my-datepicker" ).datepicker();
}

I don't know why it messes up when that happens, but regardless, this patches it back up again.

No comments:

Post a Comment