Here am trying to add a html rows by clicking on the add button and delete the added rows on clicking on the delete button.
Its working fine with adding rows as expected. But the problem is the delete function deletes the last row of the table instead of deleting that corresponding row.
As there is delete button in every row, only that corresponding row should be deleted when the delete button is clicked.
Here is the jsfiddle which demonstrates the situation better.
if the fiddle above failed to load as it does, Please refer the code below.
Thanks in advance
JAVSCRIPT
//function to add a row
function insSpec()
{
rl=document.getElementById("insSpecc").rows.length;
var a=document.getElementById("insSpecc").insertRow(rl);
var h=a.insertCell(0);
var f=a.insertCell(1);
var m=a.insertCell(2);
var n=a.insertCell(3);
h.innerHTML='<div class="separator"><input type="text" name="client_prod[]" class="separator" id="competitor_prod'+rl+'" style="width:150px" >';
f.innerHTML='<input type="text" name="client_nrx[]" id="client_nrx'+rl+'" size="5" />';
m.innerHTML='<input type="text" name="client_rrx[]" id="client_rrx'+rl+'" size="5" />';
n.innerHTML='<button class="del_img" onClick="delSpec('+rl+')">Delete</button></div>';
}
//function to delete a row
function delSpec(rl)
{
r=document.getElementById("insSpecc").rows.length;
if(r!=2)
{
document.getElementById("insSpecc").deleteRow(r-1)
}
}
HTML
<table id="insSpecc" width="100%;">
<div class="separator">
<tr>
<td><span>Product</span></td>
<td><span>NRX(Qty)</span></td>
<td><span>RRX(Qty)</span></td></tr></div>
<tr>
<td><input type="text" id="client_prod" name="client_prod[]" style="width:150px;" class="validate[required] text-input"></td>
<td>
<input type="text" id="client_nrx" name="client_nrx[]" size="5" class="validate[required] text-input">
</td>
<td>
<input type="text" id="client_rrx" name="client_rrx[]" size="5">
</td>
<td>
<button id="add_img" id='insSpecimg' style='display:block;' onClick="insSpec()" align="center">Add</button>
</td>
</tr>
</table>
Try to use
and later
in such case delSpec will receive pointer to the button, and will be able to delete the necessary row.