Reputation: 133
I am dynamically generating table rows using the following javascript codes:
$('#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();
});
And this is my script for appending jQuery calendar to date inputs
$(function() {
$('input').filter('.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
});
Now the problem I am facing is that the jQuery calendar pops up only in the first row. It doesn't work on the rows that are generated.
This in my html
<td>
<input type="text" class="form-control datepicker" name="invoiceDate[]" readonly="readonly" />
</td>
Please tell me how to make jQuery calendar work on all the rows that are dynamically generated. Looked around Google but nothing helped.
Thanks in advance.
Upvotes: 3
Views: 2093
Reputation: 388446
You have to initiate the datepicker after the new rows are created
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,
});
}
});
<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>
Upvotes: 1
Reputation: 3964
$('#addNew').on('click',function(){
.....
.....
addDP();
});
addDP();
function addDP(){
$('input').filter('.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
}
Upvotes: 0