JQuery datepicker for dynamically generated strings
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 to add jQuery calendar to current inputs
$(function() {
$('input').filter('.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
});
Now the problem is the jQuery calendar only appears on the first line. It doesn't work with strings that are generated.
This is in my html
<td>
<input type="text" class="form-control datepicker" name="invoiceDate[]" readonly="readonly" />
</td>
Explain how to make jQuery calendar for all dynamically generated rows. Looked around google but nothing helped.
Thanks in advance.
+3
source to share
2 answers
After creating new lines, you need to initiate datuping.
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>
+1
source to share