Thursday, September 24, 2009

Adding Dynamic rows to table using javascript

Please copy this code and create as test.html and see the functionality

<html>
<head>
<script LANGUAGE="JavaScript">
function addRow(tableID){
var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name = "empNo";
cell1.appendChild(element1);

var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
cell2.appendChild(element2);

var cell3 = row.insertCell(2);
var element3 = document.createElement("textarea");
element3.setAttribute("name","mytextarea");
element3.setAttribute("cols","10");
element3.setAttribute("rows","1");
cell3.appendChild(element3);
}
function deleteRow(tableID) {

var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount > 1) {
table.deleteRow(rowCount - 1);
}

}
</script>
</head>
<body>
<form name="f1" id="f1">
<input type="button"value="Add" onclick="addRow('datatable')">
<table id="datatable" cellspacing="0" border="1" bgcolor="#738711">
<tbody>
<tr>
<td><input type="text" ></td><td><input type="text"></td><td><textarea rows="1" cols="10"></textarea></td>

<td><a href="javascript:void(0);" onclick="deleteRow('datatable')" >Remove</a></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

2 comments:

CSB said...

How to put row id dynamically..help me out from this---CSB

Mallik said...

After creating the row at this line: var row = table.insertRow(rowCount);


you can add the dynamic id value as below

row.id="idName";