I have two functions to add and remove table rows that contain a form input element. They both work fine, but I have a problem in that I need to show a Remove button input only on subsequently created table rows. My two function are as as follows:
function addRow(table_id){
var clone;
var rows=document.getElementById(table_id).getElementsByTagName('tr');
var index=rows.length;
var tbo=document.getElementById(table_id).getElementsByTagName('tbody')[0];
clone=rows[index-1].cloneNode(true);
tbo.appendChild(clone);
}
function delRow(table_id,button){
var row = button.parentNode.parentNode;
var tbo = document.getElementById(table_id).getElementsByTagName('tbody')[0];
tbo.removeChild(row);
}
and the html content is:
<form>
<table id="mytab">
<tr>
<td>Upload File <input type="file" name="uploadfile[]" onchange="addRow('mytab')" /> <input name="del_row" type="button" value="Remove Row" onclick="delRow('mytab',this)"/></td>
</tr>
</table>
</form>
I am by no means a Javascript expert - more of a newbie - so I'm struggling to come up with a solution.
I'm assuming that you are trying to avoid having the remove button in the first row, but need it there now because you think that to get it in subsequent rows, you need to have it in the row that you are cloning. If, instead, you just insert new HTML for both the upload and delete button inputs in the addRow method you can avoid the clone entirely and it won't matter what your original row contains.
function addRow(table_id){
var table = document.getElementById(table_id);
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
var template = table.rows[0].cells[0].innerHTML;
cell.innerHTML = template + '<input type="button" value="Remove Row"'
+ ' onclick="delRow(\'' + table_id + '\',this);" />'
}
This still uses the first row as the template, but you can remove the button from it as it is added by appending to the existing text.