Reputation: 31
I am using a script to add a row to my form table which is working absoulty fine. On my first input box I am using a datepicker which is working on the first row but when I add another row the datepicker isnet working. I'm assuming it's because there is no class. I have tried adding using this bit of code but with no luck: newcell.className = 'datepicker';
function addRow(tableID) {
var table = document.getElementById(tableID).getElementsByTagName('tbody')[0];
var rowCount = table.rows.length;
if(rowCount < 50){ // limit the user from creating fields more than your limits
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;
newcell.className = 'datepicker';
}
}else{
alert("Too many rows.");
}
}
Upvotes: 3
Views: 5522
Reputation: 8472
You need to actually create the datepicker on the element, at the end of the for-loop body. Also, don't copy the innerHTML
of the original row, as will also copy the id
of the input, which must be unique and will break the date picker logic.
A complete working example is below.
function addRow(tableID) {
var table = document.getElementById(tableID).getElementsByTagName('tbody')[0];
var rowCount = table.rows.length;
if(rowCount < 50){ // limit the user from creating fields more than your limits
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.appendChild(document.createElement('input'));
$(newcell).find('input').addClass('datepicker');
$(newcell).find('input.datepicker').datepicker();
}
}else{
alert("Too many rows.");
}
}
$(function () {
$('.datepicker').datepicker();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"/>
<button onclick="addRow('table')">Add Row</button>
<table id="table">
<tbody>
<tr>
<td><input class="datepicker" /></td>
</tr>
</tbody>
</table>
Upvotes: 2