Dynamically Add/Remove Rows to HTML Table using JavaScript

← PrevNext →

Last update: 21st August 2023

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.

add remove table rows using javascript

Related Posts:

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) How to reead data from an HTML table using JavaScript. This quick tip explains how you can easily read data from a table, column wise or the entire table, using a simple script.

See this demo
The Markup

In the markup section, there are 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 to the <div> element.

<!DOCTYPE html>
<html>
<head>
    <style>
        table { width: 100%; }
        table, th, td { 
            border: solid 1px #DDD;
            border-collapse: collapse; 
            padding: 2px 3px; 
            text-align: center;
        }
    </style>
</head>
<body onload="createTable()">
    <p>
        <input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
    </p>
    <div id="cont"></div>   <!--the container to add the table.-->
    <p><input type="button" id="bt" value="Submit Data" onclick="submit()" /></p>

    <p id='output'></p>
</body>

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.

The Script
<script>
    let arrHead = new Array();
    arrHead = ['', 'Employee Name', 'Designation', 'Age'];      // table headers.

    // first create a TABLE structure by adding few headers.
    let createTable = () => {
        let empTable = document.createElement('table');
        empTable.setAttribute('id', 'empTable');  // table id.

        let tr = empTable.insertRow(-1);

        for (let h = 0; h < arrHead.length; h++) {
            let th = document.createElement('th'); // the header object.
            th.innerHTML = arrHead[h];
            tr.appendChild(th);
        }

        let div = document.getElementById('cont');
        div.appendChild(empTable);    // add table to a container.
    }

    // function to add new row.
    let addRow = () => {
        let empTab = document.getElementById('empTable');

        let rowCnt = empTab.rows.length;    // get the number of rows.
        let tr = empTab.insertRow(rowCnt); // table row.
        tr = empTab.insertRow(rowCnt);

        for (let c = 0; c < arrHead.length; c++) {
            let td = document.createElement('td');          // table definition.
            td = tr.insertCell(c);

            if (c == 0) {   // if its the first column of the table.
                // add a button control.
                const button = document.createElement('input');

                // set the attributes.
                button.setAttribute('type', 'button');
                button.setAttribute('value', 'Remove');

                // add button's "onclick" event.
                button.setAttribute('onclick', 'removeRow(this)');

                td.appendChild(button);
            }
            else {
                // the 2nd, 3rd and 4th column, will have textbox.
                const ele = document.createElement('input');
                ele.setAttribute('type', 'text');
                ele.setAttribute('value', '');

                td.appendChild(ele);
            }
        }
    }

    // function to delete a row.
    let removeRow = (oButton) => {
        let empTab = document.getElementById('empTable');
        empTab.deleteRow(oButton.parentNode.parentNode.rowIndex); // buttton -> td -> tr
    }

    // function to extract and submit table data.
    let submit = () => {
        let myTab = document.getElementById('empTable');
        let arrValues = new Array();

        // loop through each row of the table.
        for (let row of myTab.rows) {
          for (let cell of row.cells) {
            if (cell.childNodes[0] != undefined)
            {
              if (cell.childNodes[0].nodeName == 'INPUT' &&  
                  cell.childNodes[0].type == 'text') {
            
                if (cell.childNodes[0].value != '')
            	    arrValues.push("'" + cell.childNodes[0].value + "'");
              }
            }
          }
        }
        
        // The final output.
        document.getElementById('output').innerHTML = arrValues;
    }
</script>
</html>
Try it

1) The first method "createTable()" in the script, creates the table. For table 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: How to convert JSON dynamically to an HTML Table using JavaScript

1) 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 this demo

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

function removeRow(oButton) { }

It removes (or deletes) the entire row. Please see 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.

Happy Coding. 🙂

← PreviousNext →