Hey guys,
I have a table which contains a link to add rows in each row after the header. This link, when clicked, adds a row beneath the row which contained the clicked link. This part works perfectly.
However the added rows each have a link to remove themselves from the table, and this is the part which isn't working properly. What's supposed to happen is that you click on a link, and then the row which contains the link you just clicked on is deleted.
What's actually happening is when the "remove" links are clicked, first the row 2 rows above it is removed, then the row directly above it,
then the correct row (itself) is deleted.
Hope all of that makes sense!
This is my script:
Code:
function addRowToTable(thisRow)
{
var tbl = document.getElementById('foodsTable');
addedRow = thisRow + addedRows;
var row = tbl.insertRow(addedRow);
row.id = addedRows;
addedRows = addedRows + 1;
var cellLeft = row.insertCell(0);
cellLeft.innerHTML = " + <input type='text'> <a href='JavaScript:removeRowFromTable(" + row.id + ")'>Remove</a>";
var cellMiddle = row.insertCell(1);
cellMiddle.innerHTML = "<input type='text'>";
var cellRight = row.insertCell(2);
cellRight.innerHTML = "text here";
}
function removeRowFromTable(i)
{
var tbl = document.getElementById('foodsTable');
document.getElementById('foodsTable').deleteRow(i)
addedRows = addedRows - 1;
}
And this is my table:
Code:
<table width=100% id="foodsTable">
<tr bgcolor="#EEEEEE">
<td width=*><b>Food/Drink</b></td>
<td align="right" width=100><b>Purchased</b></td>
<td align="right" width=100><b>Produced</b></td>
<td width=60></td>
</tr>
<tr>
<td><a href="itemdetails.php?item=Apples" onMouseover="ddrivetip('<?php getToolTipData('Apples',$Foods); ?>')"; onMouseout="hideddrivetip()">Apples</a>
<a href="JavaScript:addRowToTable(2)">+ Add similar food</a>
<font color="#FF0000">*NEW*</font></td>
<td align="right"><input type="text" name="Apples" maxlength="10" size="10" value="<?php echo $session->foodsApplesPurc; ?>" style="text-align:right" /></td>
<td align="right"><input type="text" name="ApplesProd" maxlength="10" size="10" value="<?php echo $session->foodsApplesProd; ?>" style="text-align:right" /></td>
<td>kg/week</td>
</tr>
<!-- many more rows just like the one above /-->
</table>
I've
highlighted the sections which I believe are most likely to be the source of my problems. Please ignore the PHP and mouseover/mouseout parts - I don't think they're relevant to this particular problem. I'm also not bothered at this stage by the fact that I'm not adding enough cells to the new rows - I'll fix this later. At this stage I just want to get the "remove" links to remove their own rows.
Any ideas? Knowing me it's most likely a case of me making it way more complicated than it needs to be, and digging myself into a hole! I will be eternally indebted to anyone who can give me any help!
Thanks in advance!