I encountered an issue with the datepicker when adding it to dynamically added rows. The datepicker was not functioning properly on the added rows, except for the first row where it worked perfectly. Strangely, removing the first row resulted in the datepicker working correctly on the remaining added rows.
Below is the code snippet:
$(function() {
$( ".datepicker" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
maxDate: new Date(),
dateFormat: 'yy-mm-dd',
numberOfMonths: 1,
}); });
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
var $row = $(row);
$row.find('input.datepicker').datepicker({
maxDate: new Date(),
dateFormat: 'yy-mm-dd',
});
}
Here is the HTML code corresponding to the JavaScript above:
<input type="button" class="btn btn-default" value="Add Row" onClick="addRow('add_row')"/>
<table class="table table-bordered" id="adddeleterow">
<tbody id="add_row">
<tr>
<td><input class="form-control datepicker" type="text" name="date[]" id="date" placeholder="Date"/>
</td>
<td>
<input class="form-control" type="text" name="hours[]" id="hours" placeholder="hours(hh:mm)"/>
</td>
<td><input type="button" class="btn btn-default" id="delPOIbutton" value="Delete" onClick="delete_check('add_row',this)" /></td>
</tr>
</tbody>
</table>