Search code examples
jqueryjquery-uidatepickerclone

cloned datepicker input not working


I have a datepicker input ( jquery UI) as below

<div class="row more-info-1">
<input class="pi-datepicker" type="text">
</div>

<a href="javascript:void(0)" onclick="addMoreDetails(1)">Add More</a>

I need to clone this input multiple times , so my javascript is :

$('.pi-datepicker').datepicker({ dateFormat: 'dd-mm-yy' });
function addMoreDetails(nit_quotation_id) {
    $latest_div     = $('.more-info-'+nit_quotation_id+':last');  

    $latest_div.datepicker('destroy').removeAttr('id')

    $clone          = $latest_div.clone(false);

    $latest_div.after($clone);
    $clone.find('input.pi-datepicker')
      .removeClass('hasDatepicker')
      .removeData('datepicker')
      .unbind()
      .datepicker({ dateFormat: 'dd-mm-yy' });
}

But when I clicked on the cloned input , the datepicker screen appears, but the value is changed in the first input box. Kindly check the FIDDLE


Solution

  • This is happening because of your input controls having the same ID (dd_date). Update your input control id for each time when you click 'Add More' like below.

    $clone.find('input.pi-datepicker')
      .removeClass('hasDatepicker')
      .removeData('datepicker')
      .attr('id', 'dd_date' + Math.random()) //newly added line
      .unbind()
      .datepicker({ dateFormat: 'dd-mm-yy' });
    

    Updated Fiddle DEMO