克隆的Datepicker无法正常工作

时间:2017-02-05 09:41:38

标签: jquery datepicker

我复制了以下字段。我的问题是克隆的datepicker不起作用。

<div class="col-md-12">
  <button type="button" id="childField" class="btn btn-primary btn-addon m-b-sm btn-rounded"><i class="fa fa-plus"></i> ADD FIELDS</button>
</div>
<div id="Children">
  <div class="divider col-md-12"></div>
  <div class="form-group col-md-7">
    <label for="child">Name of Child</label>
    <input type="text" class="form-control" name="child[]" id="child" placeholder="FULL NAME">
  </div>

  <div class="form-group col-md-5">
    <label for="ch_DateOfBirth">Date of Birth</label>
    <input type="text" class="form-control date-picker" name="ch_DateOfBirth" id="DateOfBirth" placeholder="Date of Birth">
  </div>
</div>

这是我用于复制字段的jQuery。

&#13;
&#13;
$(document).ready(function() {
    $('#childField').click(function() {
        $('#Children').clone().insertAfter("#Children");
    });
});
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

当您克隆某些HTML时,它会松开它的事件绑定,因此您必须重新初始化事件,在这种情况下,日期选择器使用它自己的事件绑定。

并且您也无法使用多个相同的ID,因此您必须更改ID。

&#13;
&#13;
var idInc = 1;
$(document).ready(function() {

  $('#childField').click(function() {
    var cloned = $('#Children').clone();
    cloned.find('input').each(function() {
      var id = $(this).attr('id');
      $(this).attr('id', id + '-' + idInc);
    })
    idInc++;
    cloned.insertAfter("#Children");
    $('.date-picker').datePicker() // Whatever // You have to reinitialise
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12">
  <button type="button" id="childField" class="btn btn-primary btn-addon m-b-sm btn-rounded"><i class="fa fa-plus"></i> ADD FIELDS</button>
</div>
<div id="Children">
  <div class="divider col-md-12"></div>
  <div class="form-group col-md-7">
    <label for="child">Name of Child</label>
    <input type="text" class="form-control" name="child[]" id="child" placeholder="FULL NAME">
  </div>

  <div class="form-group col-md-5">
    <label for="ch_DateOfBirth">Date of Birth</label>
    <input type="text" class="form-control date-picker" name="ch_DateOfBirth" id="DateOfBirth" placeholder="Date of Birth">
  </div>
</div>
&#13;
&#13;
&#13;