views:

2945

answers:

2

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.

+2  A: 

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.

tvanfosson
+1  A: 

If you need to create this element

<input name="del_row" type="button" value="Remove Row" onclick="delRow('mytab',this)"/>

everytime the addRow function is called, you can just do this inside addRow();

var input = document.createElement("input");
input.setAttribute("name", "del_row");
input.setAttribute("type", "button");
input.setAttribute("value", "Remove Row");
input.onclick = function() {
    delRow("+table_id+", this);
};
Luca Matteis
I would have done this, too, but I'm so used to jQuery that I've forgotten whether the input.onclick way of assigning handlers is fully cross-browser compatible.
tvanfosson