Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically add new table row

Status
Not open for further replies.

Peppi

Programmer
Apr 9, 2001
205
CA
Hi,

I can't figure out why the following code is not adding a new row to my table:

function addNewRow(sender)
{
if(sender == null)
return;

//get a reference to the table
var table = GetParentElementByTagName(sender, "TABLE");
var row = GetParentElementByTagName(sender, "TR");
//add new row to table
var newRow = row.cloneNode(true);
table.appendChild(newRow);
}

function GetParentElementByTagName(element, tagName)
{
var element=element;
while(element.tagName != tagName)
element = element.parentNode;
return element;
}

I don't know JavaScript terribly well so I'm sure there's something simple that I'm missing.

Thx.
 
Here's an example:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

function addNewRow() {
   var tbl = document.getElementById("theTable");
   var newTR = document.createElement("tr");
   var newTD1 = document.createElement("td");
   var newTD2 = document.createElement("td");
   newTD1.appendChild(document.createTextNode('this is a'));
   newTD2.appendChild(document.createTextNode('new row'));
   newTR.appendChild(newTD1);
   newTR.appendChild(newTD2);
   tbl.appendChild(newTR);
}

</script>

<style type="text/css">

</style>
</head>
<body>

<input type="button" onclick="addNewRow()" value="add new row" />
<table id="theTable" border="1">
   <tr>
      <td>this is the</td>
      <td>original row</td>
   </tr>
</table>

</body>
</html>

It doesn't work in IE for some strange reason and I don't have time to debug it. It work fine in firefox.

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
I appended the child to the TBODY element instead of the TABLE element and now it works.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top