Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datepicker not working for cloned elements

I have a jquery date picker field which I am cloning when a user clicks on an Add button. I want the date picker to appear for the subsequently added fields on the screen. Right now the datepicker is appearing only for the first field and not for the added/cloned fields.

After checking a lot of posts on similar topic here, I was able to reach at this stage. Below is my code so far.

<div class="repeatingSection">
<a href="#" class="deleteDate" style="display: none;">-Delete</a>
<input type="text" class="dateListValues" style="position: relative; z-index:100000;" 
       id="dateListValues_1" size="15" />
</div>
<a href="#" class="addDate">+ Add</a>

JS:

// Add a new repeating section
$('.addDate').click(function(){
    var currentCount =  $('.repeatingSection').length;
    var newCount = currentCount+1;
    var newID;
    var lastRepeatingGroup = $('.repeatingSection').last();
    var newSection = lastRepeatingGroup.clone();
    newSection.insertAfter(lastRepeatingGroup);
    newSection.find("input").each(function (index, input) {
        input.id = input.id.replace("_" + currentCount, "_" + newCount);
        input.name = input.name.replace("_" + currentCount, "_" + newCount);
        input.value = "";
            //removing the additional hasDatepicker class 
        $('#'+input.id).removeClass('hasDatepicker');
    });

    return false;
});

   $('.dateListValues').each(function(){
    $(this).datepicker();
   });

Thanks.

like image 513
DarkKnightFan Avatar asked Dec 14 '12 10:12

DarkKnightFan


2 Answers

You need to initialise the datepicker plugin on the newly created element. Try adding this line right before your return false;:

newSection.find(".dateListValues").datepicker();
like image 150
Rory McCrossan Avatar answered Oct 30 '22 16:10

Rory McCrossan


initailize date picker inside the click function..

$('.addDate').click(function(){
var currentCount =  $('.repeatingSection').length;
var newCount = currentCount+1;
var newID;
var lastRepeatingGroup = $('.repeatingSection').last();
var newSection = lastRepeatingGroup.clone();
newSection.insertAfter(lastRepeatingGroup);
newSection.find("input").each(function (index, input) {
    input.id = input.id.replace("_" + currentCount, "_" + newCount);
    input.name = input.name.replace("_" + currentCount, "_" + newCount);
    input.value = "";
        //removing the additional hasDatepicker class 
    $('#'+input.id).removeClass('hasDatepicker');

});
  newSection.find(".dateListValues").datepicker(); //here
  return false;
});
like image 39
bipen Avatar answered Oct 30 '22 17:10

bipen