动态生成的行上的jQuery datepicker

时间:2015-06-01 06:08:18

标签: javascript jquery html datepicker

我使用以下javascript代码动态生成表格行:

$('#addNew').on('click', function() {
    var clone = $('table.table-responsive tr.cloneme:first').clone();
    console.log(clone);
    clone.append("<td><button class='deleteAdded btn btn-danger'>Remove</button></td>")
    $('table.table-responsive').append(clone);
    calculateSum();
});

这是我添加jQuery日历到日期输入的脚本

$(function() {
    $('input').filter('.datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
    });
});

现在我遇到的问题是jQuery日历只在第一行弹出。它不会对生成的行起作用。

这在我的HTML中

<td>
    <input type="text" class="form-control datepicker" name="invoiceDate[]" readonly="readonly" />
</td>

请告诉我如何使jQuery日历适用于动态生成的所有行。看看谷歌,但没有任何帮助。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您必须在创建新行后启动日期选择器

&#13;
&#13;
jQuery(function($) {
  //create a original copy of the row to clone later
  var $tr = $('table.table-responsive tr.cloneme:first').clone();

  //add dp to existing rows
  addDP($('input.datepicker'));

  $('#addNew').on('click', function() {
    var clone = $tr.clone();
    console.log(clone);
    clone.append("<td><button class='deleteAdded btn btn-danger'>Remove</button></td>");
    //add dp to the new row
    addDP(clone.find('input.datepicker'));
    $('table.table-responsive').append(clone);
    calculateSum();
  });

  function addDP($els) {
    $els.datepicker({
      dateFormat: 'yy-mm-dd',
      changeMonth: true,
      changeYear: true,
    });
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<table class="table-responsive">
  <tr class="cloneme">
    <td>
      <input type="text" class="form-control datepicker" name="invoiceDate[]" readonly="readonly" />
    </td>
  </tr>
</table>
<button id="addNew">Add</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$('#addNew').on('click',function(){
    .....
    .....
    addDP();
});

addDP();

function addDP(){

    $('input').filter('.datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
    });

}