具有输入的动态创建行上的datepicker

我有一个表单,可以动态创建带输入的新行,每个新行上的日期输入应该有一个datepicker。 我有这个几乎工作,但是当创建带输入的新行时,datepicker将不再适用于已存在的日期字段。 我玩了整整一天来找出我做错了什么,但我只是看不出如何解决这个问题。

这是小提琴 – > http://jsfiddle.net/HermesTrismegistus/vdFaH

我的表单看起来像这样:

Product Datum Tijd Minuten

我有的jquery,看起来像这样:

  $(function(){ // start a counter for new row IDs // by setting it to the number // of existing rows $('.datepick').datepicker(); var newRowNum = 0; // bind a click event to the "Add" link $('#addnew').click(function(){ // increment the counter newRowNum = $(productTable).children('tbody').children('tr').length +1; // get the entire "Add" row -- // "this" refers to the clicked element // and "parent" moves the selection up // to the parent node in the DOM var addRow = $(this).parent().parent(); // copy the entire row from the DOM // with "clone" var newRow = addRow.clone(); // set the values of the inputs // in the "Add" row to empty strings $('input', addRow).val(''); // insert a remove link in the last cell $('td:last-child', newRow).html(''); // insert the new row into the table // "before" the Add row addRow.before(newRow); // add the remove function to the new row $('a.remove', newRow).click(function(){ $(this).closest('tr').remove(); return false; }); $('#date', newRow).each(function(i){ var newID = 'date_' + i; $(this).attr('id',newID); }); // prevent the default click return false; }); 

试试这个,当你添加一行时,销毁所有的datepicker实例,然后在追加一个新行后重新绑定datepicker。

jsFiddle示例

在我的例子中,我使用clone()来创建一个datepicker的副本。

$(".cloneDiv").clone().appendTo("#copyHolder");

然后我删除了datepicker添加到输入元素的“class”和“id”。

$(".hasDatepicker").removeClass("hasDatepicker").removeAttr("id");

注意:由于要克隆输入元素,我不给它们“id”属性。 所以datepicker会自动为我的DOM元素添加“id”。 另外,如果要克隆的元素具有用户分配的“id”,这意味着将至少有两个元素共享相同的“id”,则datepicker将有一些问题需要找到正确的元素。 一个例子可以在@ j08691的答案中找到。

最后,将datepicker重新绑定到输入元素:

$(".inputDate").datepicker();

具有类“inputDate”的所有输入元素都将具有datepicker。

Chrome控制台中显示javascript错误:

 Uncaught TypeError: Cannot read property 'inline' of undefined 

这可能会关闭datepickerfunction。

销毁datepicker并在添加新行后再次创建。 它将解决问题。

这是一个例子

 jQuery( ".datepick" ).datepicker(); //Add date picker. $('#addnew').click(function(){ $(".datepick").datepicker("destroy"); //Distroy the date picker. /* Code to add a new row */ jQuery( ".datepick" ).datepicker(); //recreating the date picker })