views:

239

answers:

1

Hey,

I have an input field that I define as a datepicker through a css class. I now want to clone this input field and have it so the cloned inputs are also datepickers.

After reading from various sources I was lead to believe that the following code should work but it doesn't. I was hoping maybe someone could help me figure out what I was doing wrong :)

<input type="text" id="date" name="date" class="calendar" />
<input type="button" id="clone" name="clone" value="Clone dates" />

And here's the javascript:

<script type="text/javascript">
$(document).ready(function(){

 $('.calendar').datepicker();

 $('#clone').click(function()
 {
  $('.calendar:last').clone().append().insertAfter('.calendar:last');
 });

});

</script>

So far the input field is duplicated and is inserted at after the last instance but the datepicker doesn't work. I tried passing 'true' to the clone function but it gave me an error saying that inst wasn't defined.

Any help would be appreciated :)

+2  A: 

Change it to this:

$('.calendar:last').clone(false).removeClass('hasDatepicker').insertAfter('.calendar:last').datepicker();
David Morton
It clones the input but it doesn't create the datepicker object (it doesn't give an error either which makes it even more confusing)
Gazillion
Apparently you have to remove the 'hasDatepicker' class before calling datepicker() again. I've updated the post.
David Morton
Thanks! That fixed it!
Gazillion
I played around with the code to understand it a bit more and it seems jQuery uses that class name as a flag to know whether the input has already been initialized. Adding it to a second input keeps the object from becoming a datepicker. Interesting :) Thanks again, I'll go to bed smarter tonight!
Gazillion