Why does jQuery UI's datepicker break with a dynamic DOM?

Will Morgan picture Will Morgan · Jun 29, 2009 · Viewed 35.5k times · Source

I'm working with a dynamic DOM here, and have called the jQuery UI datepicker to all inputs with a specific class name, in this case .date

It works great with the first, static, construct but when I clone it the event handlers don't seem to want to move over. I get the Firebug error:

inst is undefined

I tried looking into jQuery's new live() function but couldn't combine the two. Any ideas?

Answer

Will Morgan picture Will Morgan · Jun 29, 2009

Ah, got it. Right after I append the HTML to the DOM I run this on all the inputs I'd like to have a datepicker pop up with. Datepicker adds a class to elements it has been attached to, so we can filter out existing inputs and only apply it to new ones.

$('.date').not('.hasDatePicker').datepicker();

I hope this helps people as I was Googling for days and didn't find anything!

You should also note that it would be faster to check for input.date in the new generated HTML by setting that as a context, rather than the whole page, as it will save time, due to this being a more efficient operation.