Dynamically Add/Remove rows in HTML table using JavaScript

This is very often for web developer when we need to use dynamically generate HTML table using JavaScript. The example will spare the first row(cannot delete) and you can dynamically add new row by clicking the button Add Row or delete the row by clicking the button Delete Row.

The Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <title>Add/Remove dynamic rows in HTML table </title>
    <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 = "checkbox";
            var cell2 = row.insertCell(1);
            cell2.innerHTML = rowCount + 1;
            var cell3 = row.insertCell(2);
            var element2 = document.createElement("input");
            element2.type = "text";

        function deleteRow(tableID) {
            try {
                var table = document.getElementById(tableID);
                var rowCount = table.rows.length;
                for (var i = 0; i < rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[0];
                    if (null != chkbox && true == chkbox.checked) {  
            catch (e) {

    <input type="button" value="Add Row" onclick="addRow('dataTable')" />
    <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
    <table id="dataTable" width="350px" border="1">
                <input type="checkbox" name="chk" />
                <input type="text" />

Output Example

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example