Dynamically Add/Remove rows in HTML table using JavaScript
Posted by Raj
This article shows you how to add/delete rows to an HTML table dynamically, using DHTML and JavaScript.The code has been tested to work with Firefox . It may work with other browsers.The sample code has two JavaScript functions - one to add new rows and the other to delete rows.
Example:
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(table_Id) {
var table = document.getElementById(table_Id);
var rowCnt = table.rows.length;
var row = table.insertRow(rowCnt);
var RowCell1 = row.insertCell(0);
var e = document.createElement("input");
e.type = "checkbox";
RowCell1.appendChild(e);
var RowCell2 = row.insertCell(1);
RowCell2.innerHTML = rowCnt + 1;
var RowCell3 = row.insertCell(2);
var e2 = document.createElement("input");
e2.type = "text";
RowCell3.appendChild(e2);
}
function deleteRow(table_Id) {
try {
var table = document.getElementById(table_Id);
var rowCnt = table.rows.length;
for(var i=0; i<rowCnt; i++) {
var row = table.rows[i];
var selected_chkbox = row.cells[0].childNodes[0];
if(null != selected_chkbox && true == selected_chkbox.checked) {
table.deleteRow(i);
rowCnt--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<TABLE id="table_Id" border="1">
<TR>
<TD><INPUT type="checkbox" name="chekbx"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
<INPUT type="button" value="ADD ROW" onclick="addRow('table_Id')" />
<INPUT type="button" value="DELETE ROW" onclick="deleteRow('table_Id')" />
</BODY>
</HTML>
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under
how to add javascript,
JAVASCRIPT
.You can leave a response, or trackback from your own site.