I have a table that looks like:
<table id="mytable" border="2" width="640px">
<tr>
<td></td>
<td><b>Col 1</b></td>
<td><b>Col 2</b></td>
<td><b>Col 3</b></td>
<td><b>Col 4</b></td>
<td><b>Col 5</b></td>
<td><b>Col 6</b></td>
<td><b>Col 7</b></td>
</table>
and a function to add a row and cells in the row that looks like:
function addRow() {
//add a row to the table keeping track of last row in table
noRows = noRows+1;
var newRow = document.getElementById("mytable").insertRow(noRows);
//add cells to new row with a unique tag and set the innerHTML to contain text boxes
var oCell = newRow.insertCell(0);
oCell.innerHTML = "<input type='button' value='x' onclick='removeRow(this);'/>";
for (c=1; c<8; c++) {
tag = "t"+noRows.toString()+c.toString();
oCell = newRow.insertCell();
oCell.innerHTML = "<input type='text' id=tag>";
}
}
The problem is the insertCell won't insert that first cell with an x in it (which will allow users to click on the x button to delete the row) in the first cell in Google Chrome. Firefox inserts a row with the first cell containing the x button but no other cells with the text boxes.
I've tried setting the index on the cell insert to 0, 1, 8, nothing and Chrome either inserts a row with nothing in it (no text boxes, no x button, nothing other than a slight addition of space below the title row) or it adds the row correctly except the x button always winds up in the last cell. IE adds it correctly with no index value or 0. Firefox needs the 0 index (no index creates a blank row with nothing in it. It looks like there's a tiny blank row of nothing being inserted because you see the table get a tiny bit larger vertically but there is no x button, text boxes.
What am I doing wrong? How do I make this work in all 3 browsers? Well actually all browsers ideally but....
Further, if I supply the 0 index to get a row, clicking on the x button to delete it works correctly in IE and Chrome but does nothing in Firefox. That code looks like:
function removeRow(src){
/* src refers to the input button that was clicked.
to get a reference to the containing <tr> element,
get the parent of the parent (in this case <tr>)
*/
var oRow = src.parentElement.parentElement;
//once the row reference is obtained, delete it passing in its rowIndex
document.getElementById("mytable").deleteRow(oRow.rowIndex);
noRows = noRows-1;
}
So what is wrong with both the addRow and removeRow functions that is causing Chrome and Firefox to behave incorrectly?