Dynamically adding rows with jquery datepicker elementes

While I was working on a solution where I have added two datepickers to a row along with add button to add new row with datepickers dynamically.

This was very easy to clone the row and append as new but datepickers were not working because they either needs to be refreshed or created again.

To get datepickers working with new row you need to do following

  1. The id of the datepicker element should be unique (if the row was cloned then id of datepicker was same you need to change it)
  2. you need to remove the .hasDatepicker class
  3. you need to call the destroy method to remove all previous datepicker data
var id = 1;
function addDatepicker($newRow) {
    $newRow.find(".datepicker").datepicker( "destroy" );

    //in case you have two date pickers in a row
    $newRow.find(".datepicker:eq(0)").attr('id', "newdatepicker" + (id + 1));
    $newRow.find(".datepicker:eq(1)").attr('id', "newdatepicker" + (id + 2));
    //apply datepickers

    //increment in id for next new rows, if you have two date pickers in a row then incremente it by 2

    id += 2;


The code above assumes you have two datepickers in a row, if you have one datepicker in a row then you need to increment id by just 1 and need to replace following code

$newRow.find(".datepicker:eq(0)").attr('id', "newdatepicker" + (id + 1));
$newRow.find(".datepicker:eq(1)").attr('id', "newdatepicker" + (id + 2));

with this code below

$newRow.find(".datepicker").attr('id', "newdatepicker" + (id + 1));


Leave a Reply

Your email address will not be published. Required fields are marked *