View Single Post
Old 09-25-2012, 11:51 PM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,555
Thanks: 62
Thanked 4,054 Times in 4,023 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
This code is actually *NOT* the preferred way to add a row to a table:
Code:
function addTableRow() {
    var newrow = document.createElement('tr');
    // give your table an id..
    var theTable = document.getElementById('table1');
    theTable.appendChild(newrow);
    ...
The better way is this:
Code:
function addTableRow() {
    var tbl = document.getElementById("theTable");
    var newrow = tbl.insertRow(tbl.rows.length);
Complete working example:
Code:
<html>
<body>
<table id="theTable">
<tr><td>row 1</td></tr>
<tr><td>row 2</td></tr>
<tr><td>row 3</td></tr>
<tr><td>row 4</td></tr>
</table>
<input id="theButton" type="button" value="remove last row"/>
<input id="otherButton" type="button" value="clone last row"/>
<script type="text/javascript">
document.getElementById("theButton").onclick = 
  function() {
      var tbl = document.getElementById("theTable");
      var tbody = tbl.getElementsByTagName("tbody")[0];
      var rows = tbody.getElementsByTagName("tr");
      if ( rows.length > 0 )
      {
          tbody.removeChild( rows[rows.length-1] );
      }
  }
document.getElementById("otherButton").onclick = 
  function() {
    var tbl = document.getElementById("theTable");
    var newrow = tbl.insertRow(-1);
    var newcell = newrow.insertCell(-1);
    newcell.innerHTML = "row " + tbl.rows.length;
  }
</script>
</body>
</html>
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is online now   Reply With Quote