duplicating jQuery datepicker

Question!

The datepicker function only works on the first input box that is created.

I'm trying to duplicate a datepicker by cloning the div that is containing it.

<a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="example" value="(add date)" />
</div>

To initialize the datepicker, according to the jQuery UI documentation I only have to do $('#example').datepicker(); and it does work, but only on the first datepicker that is created.

The code to duplicate the div is the following:

$("a#dupMe").click(function(event){
    event.preventDefault();
    i++;
    var a = $("#template").clone(true).insertBefore("#template").hide().fadeIn(1000);
    a.find("input#txt").attr('value', i);
    a.find("input#example").datepicker();
});

The strangest thing is that on the document.ready I have:

$('#template #example').datepicker();
$("#template #txt").click(function() { alert($(this).val()); });

and if I click on the #txt it always works.



Answers

I use a CSS class instead:

<input type="text" id="BeginDate" class="calendar" />
<input type="text" id="EndDate" class="calendar" />

Then, in your document.ready function:

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

Using it that way for multiple calendar fields works for me.

By : Dave Ward


I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template div (to be called after each duplication). Something like:

function makeDatePickers() {
    $("#template input[type=text]").datepicker();
}


This video can help you solving your question :)
By: admin