jQuery Datepicker doesn’t work on cloned elements

I tabled this issue for a while, trying not to spend too much time on it. But, it came back to haunt me in another project.

If you attempt to clone an element with jQuery's clone() method, you'll find that you are unable to apply a Datepicker() to the element.

The reason is, when you clone an element, you also clone it's class attribute. In the case of a Datepicker element, that class is "hasDatepicker".

<input class="hasDatepicker" name=... />

When the Datepicker method is called on an element, it first checks to see if that element already has the hasDatepicker class.

So, we need to remove this class before applying the Datepicker method, i.e.

$(this).removeClass('hasDatepicker').datepicker();

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs


Tagged .

Updated: 2012-01-04

Phil LaNasa follow us in feedly