Dynamically Add or Remove Table Rows in JavaScript and Save Data to a Database

I have recently shared a post on how to add or remove rows to an HTML table dynamically in AngularJS. Now, if you are a JavaScript enthusiast, then this post is for you. Here, I am sharing an example on how to add or remove table rows using plain JavaScript and save the data to a database.

You may check the demo first.

See the Demo

Before I proceed with my example, I want to check some posts that I have written before on dynamically created tables and elements associated with a table, in JavaScript.

1) How do you create an entire HTML table dynamically in JavaScript? This post will help beginners to understand the basics of creating dynamic elements in JavaScript. It also explains about JavaScript createElement() method.

2) Read data from HTML table using JavaScript. This quick tip explains how you can easily read data from a table, column wise or the entire table.

The Markup

On my web page, I have two buttons and a <div> element (as container). I’ll use the first button to add new rows to the table. However, first I need a table. I’ll create the <table> dynamically when the page first loads and add the table it the <div> element.

To remove rows in the table, I’ll add dynamically created buttons (using JavaScript) in each row of the table.

For data entry, I’ll create and add textboxes in each cell, dynamically.

The second button will submit the data in the table.

<!DOCTYPE html>
<html>
<head>
    <title>Dynamically Add Remove Table Rows in JavaScript</title>
</head>
<body onload="createTable()">
    <p>
        <input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
    </p>

    <!--THE CONTAINER WHERE WE'll ADD THE DYNAMIC TABLE-->
    <div id="cont"></div>

    <p>
        <input type="button" id="bt" value="Sumbit Data" onclick="sumbit()" />
    </p>
</body>
The Script
<script>
    // ARRAY FOR HEADER.
    var arrHead = new Array();
    arrHead = ['', 'Emp. Name', 'Designation', 'Age'];      // SIMPLY ADD OR REMOVE VALUES IN THE ARRAY FOR TABLE HEADERS.

    // FIRST CREATE A TABLE STRUCTURE BY ADDING A FEW HEADERS AND
    // ADD THE TABLE TO YOUR WEB PAGE.
    function createTable() {
        var empTable = document.createElement('table');
        empTable.setAttribute('id', 'empTable');            // SET THE TABLE ID.

        var tr = empTable.insertRow(-1);

        for (var h = 0; h < arrHead.length; h++) {
            var th = document.createElement('th');          // TABLE HEADER.
            th.innerHTML = arrHead[h];
            tr.appendChild(th);
        }

        var div = document.getElementById('cont');
        div.appendChild(empTable);    // ADD THE TABLE TO YOUR WEB PAGE.
    }

    // ADD A NEW ROW TO THE TABLE.s
    function addRow() {
        var empTab = document.getElementById('empTable');

        var rowCnt = empTab.rows.length;        // GET TABLE ROW COUNT.
        var tr = empTab.insertRow(rowCnt);      // TABLE ROW.
        tr = empTab.insertRow(rowCnt);

        for (var c = 0; c < arrHead.length; c++) {
            var td = document.createElement('td');          // TABLE DEFINITION.
            td = tr.insertCell(c);

            if (c == 0) {           // FIRST COLUMN.
                // ADD A BUTTON.
                var button = document.createElement('input');

                // SET INPUT ATTRIBUTE.
                button.setAttribute('type', 'button');
                button.setAttribute('value', 'Remove');

                // ADD THE BUTTON's 'onclick' EVENT.
                button.setAttribute('onclick', 'removeRow(this)');

                td.appendChild(button);
            }
            else {
                // CREATE AND ADD TEXTBOX IN EACH CELL.
                var ele = document.createElement('input');
                ele.setAttribute('type', 'text');
                ele.setAttribute('value', '');

                td.appendChild(ele);
            }
        }
    }

    // DELETE TABLE ROW.
    function removeRow(oButton) {
        var empTab = document.getElementById('empTable');
        empTab.deleteRow(oButton.parentNode.parentNode.rowIndex);       // BUTTON -> TD -> TR.
    }

    // EXTRACT AND SUBMIT TABLE DATA.
    function sumbit() {
        var myTab = document.getElementById('empTable');
        var values = new Array();

        // LOOP THROUGH EACH ROW OF THE TABLE.
        for (row = 1; row < myTab.rows.length - 1; row++) {
            for (c = 0; c < myTab.rows[row].cells.length; c++) {   // EACH CELL IN A ROW.

                var element = myTab.rows.item(row).cells[c];
                if (element.childNodes[0].getAttribute('type') == 'text') {
                    values.push("'" + element.childNodes[0].value + "'");
                }
            }
        }
        console.log(values);
    }
</script>
</html>

See the Demo

The first method createTable() in the script creates the table. For tables headers (column names), I am using an array. You can simply add or remove names in the array for the columns.

For the headers, you can use a JSON array by extracting data from an external JSON file.

Related Post: Convert JSON Data Dynamically to HTML Table using JavaScript

The second method is addRow(). Here, I am creating and adding rows to the table. The first button on my web page, calls this method. Every click, adds a new row.

The method not only creates rows for the table, it also creates a button (to delete row) and textboxes in each cell or the row. The table is meant for simple data entry. A slight modification in the code and you can use the table for viewing also.

The first column will have a button for each newly created row. The remaining columns will have textboxes. See how I am using the createElement() method to create new elements dynamically and the setAttribute() method to add attributes to the elements.

See the Demo

The third method is removeRow(). The method takes a parameter as element (button in this case).

function removeRow(oButton) { }

As the name says, it removes (deletes) the entire row. Please check the second method addRow() again. Here, I am creating a button and appending it to the first column of each row. While setting the attributes to the button, I have assigned an onclick event along with the method [removeRow()] that it would call. I have also assigned a value (this) as parameter.

button.setAttribute('onclick', 'removeRow(this)');

The value this refers the element (the button). It will help identify the row in which the Remove button is located.

empTab.deleteRow(oButton.parentNode.parentNode.rowIndex);   // BUTTON -> TD -> TR.

The fourth method in the script is submit(). Here, I am extracting values from each textbox in the table and pushing the values in an array. I can now use the array to pass data to my database, calling either a Web Method or a Web API in Asp.Net.

The console.log(values), shows how the array stores the data.

Showing Values in Browser Console

Finally, you can save the data in a database using a Web Method in Asp.Net.

Well, that's it. Thanks for reading.

Previous - JavaScript .contains() Method Example – Check if Element <div> Contains a <p> ElementNext - SELECT Element Set Focus on Page Load or Expand SELECT Options on Page Load



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts:

Join our Google Plus Community and be a part of a discussion!