无法在表中的克隆行上获取日期选择器
问题描述:
I was trying to get date picker on clone rows in the table.But it is not happening
my table code as follows:
<input type="text" class="form-control dp4 dob4" autocomplete="off" name="date[]" required>
<input type="button" class="btn btn-default addButton" value="Add" />
and javascript for clone row as follows:
$(function() {
$("#table-data").on('click', 'input.addButton', function() {
var $tr = $(this).closest('tr');
var allTrs = $tr.closest('table').find('tr');
var lastTr = allTrs[allTrs.length - 1];
var $clone = $(lastTr).clone();
$clone.find('td').each(function() {
var el = $(this).find(':first-child');
var id = el.attr('id') || null;
if (id) {
var i = id.substr(id.length - 1);
var prefix = id.substr(0, (id.length - 1));
el.attr('id', prefix + (+i + 1));
el.attr('name', prefix + (+i + 1));
}
});
$clone.find('input:text').val('');
$tr.closest('table').append($clone);
});
$("#table-data").on('change', 'select', function() {
var val = $(this).val();
$(this).closest('tr').find('input:text').val(val);
});
});
and my date picker code as follows:
$('.dob4').datepicker({
format: 'dd-mm-yyyy',
startDate: '-0m',
autoclose: true
});
Please help to solve this issue.
Thanks.
答
There is workaround to it,
How it Works:
- Need to remove the class
hasDatepicker
from the cloned elements,because this is what is preventing thedatepicker
from getting attached to the specific element. Need to remove the
id
attribute from each of the cloned elements else.datepicker()
will assume thatdatepicker
is added to this element.After that call
.datepicker()
on cloned element.
JS Code:
$("#table-data").on('click', 'input.addButton', function () {
...
$clone.find('.dob4').removeAttr('id').removeClass('hasDatepicker');
$clone.find('.dob4').datepicker({
format: 'dd-mm-yyyy',
startDate: '-0m',
autoclose: true
});
...
});