This code snippet will help you to add rows dynamically in a html table.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert Table Row using DOM</title>
<script language="javascript">
function addRow()
{
var tbody = document.getElementById("table1").getElementsByTagName("tbody")[0];
var row = document.createElement("TR");
var cell1 = document.createElement("TD");
var inp1 =  document.createElement("INPUT");
inp1.setAttribute("type","text");
inp1.setAttribute("value","New row");
cell1.appendChild(inp1);
var cell2 = document.createElement("TD");
cell2.innerHTML = "label3";
var cell3 = document.createElement("TD");
cell3.innerHTML = "label4";
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
tbody.appendChild(row);
//alert(row.innerHTML);
}
</script>
</head>
<body>
<tableid="table1">
<tbody>
<tr>
<td><inputtype=textvalue="Original Row"></td>
<td>label1</td>
<td> label2</td>
</tr>
</tbody>
</table>
<inputtype="button"value="Insert Row"onClick= "addRow();">
</body>
</html>

Most of the code is self explanatory, so am leaving it unexplained. If anybody needs help, post your questions, will help you.

Be Sociable, Share!