I found the following code on the W3schools tutorial page.
It inserts and deletes at the top row position of a created table.
[code=php]
<html>
<head>
<script type=”text/javascript”>
// From: http://www.w3schools.com/htmldom/met_table_insertrow.asp
function insRow() {
var x=document.getElementById(‘myTable’).insertRow(0);
var y=x.insertCell(0);
var z=x.insertCell(1);
y.innerHTML=”NEW CELL1″;
z.innerHTML=”NEW CELL2″;
}
function delRow() {
document.getElementById(‘myTable’).deleteRow(0)
}
// function addRow() {} // append row to end of table
// function delAllRows() {} // delete all rows to end of table
</script>
</head>
<body>
<table id=”myTable” border=”1″>
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<br />
<input type=”button” onclick=”insRow()” value=”Insert row”>
<input type=”button” onclick=”delRow()” value=”Delete row”>
<!– want to add the following
<input type=”button” onclick=”addRow()” value=”Append row”>
<input type=”button” onclick=”delAllRows()” value=”Remove all rows”>
–>
</body>
</html>
I have two questions concerning this code: ?
1.
How do you determine the last row position in the table?
There is something called a ‘rowIndex’ but how is it used to determine the last row (first row appears to be referenced as ‘0’)
I’m assuming that if I can determine the last row position, I would be able to delete all rows of a table, but stop when the ‘rowIndex’ reaches a minimum of ‘0’ or ‘-1’ (don’t know which it might be). I don’t want to induce an error by deleting more rows than are currently displayed in the table.
Has anyone thought about this and determined a solution?
All help is much appreciated.