Adding table rows and columns in JavaScript

With insertRow() method you can insert a new row at the specified position in HTML table. After row is created, use insertCell() method to insert a table cell. Wrap this methods in JavaScript functions and you have code to dynamically add new rows and columns in the HTML table. Please try to click the buttons below …






Small
HTML
table

When you click the “Add row” button, appendRow() function is called. Function is simple, table row is inserted at the last position, and loop iterates through table cells in the first row. Why first row? Because you have to know the number of columns. For each step (cell in the first row), createCell() function creates and attaches DIV element to the newly created table cell.

// append row to the HTML table
function appendRow() {
    var tbl = document.getElementById('my-table'), // table reference
        row = tbl.insertRow(tbl.rows.length),      // append table row
        i;
    // insert table cells to the new row
    for (i = 0; i < tbl.rows[0].cells.length; i++) {
        createCell(row.insertCell(i), i, 'row');
    }
}

// create DIV element and append to the table cell
function createCell(cell, text, style) {
    var div = document.createElement('div'), // create DIV element
        txt = document.createTextNode(text); // create text node
    div.appendChild(txt);                    // append text node to the DIV
    div.setAttribute('class', style);        // set DIV class attribute
    div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
    cell.appendChild(div);                   // append DIV to the table cell
}

createCell() also sets class attribute (needed for the red and green background color) to the DIV element. It’ not necessary to create DIV element (you can append only text node to the TD element), but this is a good example of how to create and append new element to the table cell. appendColumn() is similar to the appendRow() function. For each table row, new cell is inserted to the last position in the row.

// append column to the HTML table
function appendColumn() {
    var tbl = document.getElementById('my-table'), // table reference
        i;
    // open loop for each row and append cell
    for (i = 0; i < tbl.rows.length; i++) {
        createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
    }
}

Here is code used to delete table rows and columns (“Delete both” button, calls both functions).

// delete table rows with index greater then 0
function deleteRows() {
    var tbl = document.getElementById('my-table'), // table reference
        lastRow = tbl.rows.length - 1,             // set the last row index
        i;
    // delete rows with index greater then 0
    for (i = lastRow; i > 0; i--) {
        tbl.deleteRow(i);
    }
}

// delete table columns with index greater then 0
function deleteColumns() {
    var tbl = document.getElementById('my-table'), // table reference
        lastCol = tbl.rows[0].cells.length - 1,    // set the last column index
        i, j;
    // delete cells with index greater then 0 (for each row)
    for (i = 0; i < tbl.rows.length; i++) {
        for (j = lastCol; j > 0; j--) {
            tbl.rows[i].deleteCell(j);
        }
    }
}

85 thoughts on “Adding table rows and columns in JavaScript”

  1. thanks to u pepole great code!
    i have done same like dis one but iam not set the user defined text in cell this code is very easily understand and good logic!

  2. See page http://www.ContractorInsurance.net/auto_commercial.php

    I would like to be able to let the web user have a button that would allow them to add rows or columns depending on how I lay out the form.

    For example in this case the Header is aligned vertically and the Columns should be able to expand or detract.

    I see the code above but the question then becomes…” How do I program the Column to add WITH the content of the one next to it?

    I hope that makes sense…

    Ok…to elaborate… You are a business owner that want to purchase auto insurance.

    You have twenty drivers… I would love for you to be able to type in a number or a range of numbers that would allow you enough “columns or rows” to be able to accomadate you. And they can complete the similar request to add vehicles…then submit. I am using a form to Excel and email php script from Hot Dreamweaver.

    Thank you.

  3. @S Valencia – Adding a new column with the same content shouldn’t be a problem. Instead of creating a new table cell, “content copy” will do the magic. Simply open loop for each table row and set reference to the second column (first column contains header so it shouldn’t be used). For each created table cell set innerHTML property the same as is in first column. Here is modified appendColumn() function:

    function appendColumn() {
        var tbl = document.getElementById('my_table'), // table reference
            cols = tbl.rows[0].cells.length,           // set number of columns
            i;                                         // loop variable
        // open loop for each row
        for (i = 0; i < tbl.rows.length; i++) {
            tbl.rows[i].insertCell(cols);
            // copy content from first column
            tbl.rows[i].cells[cols].innerHTML = tbl.rows[i].cells[1].innerHTML; 
        }
    }
    
  4. dbunic – thanks for your awesome work. They are very useful. I am new to webpage design and please help me on my project.

    I want to have a dynamically table with the capability of adding rows/columns just like above example. A little bit more – all existing content in each cell are retrieved from database. The values for added cells in added column/row are to be either entered or selected from dropdown list like you showed in another example:

    table
    drop
    down
    menu
    

    Thank you…

  5. @Jack – In my comment above you can see how to copy content from previous column. In your case, you only need to slightly modify loop. Instead of copying each cell just set value from input box or drop down menu. Something like this:

    // open loop for each row
    for (i = 0; i < tbl.rows.length; i++) {
        tbl.rows[i].insertCell(cols);
        // set value from input box
        tbl.rows[i].cells[cols].innerHTML = document.forms[0].myinput.value; 
    }
    
  6. @selva – This example shows how to add table row/column (expand/reduce current table). In your case you will have to read column from source table and append (or insert) to the destination table. This should not be complicated and functions from this post can be easily reused for a such purpose.

  7. thnk u dbunic i have another doubt . in a html table colums was step by step displayed to on click process using JavaScript
    pls give some code example or related url’s

  8. @selva – If I understood you well, you asked for HTML code of Add column button. No problem, here is source:

    <input type="button" value="Add column" onclick="appendColumn()" class="append_column">
    

    As you can see, on button click appendColumn() is called and its source is shown on this page.

  9. dbunic: I learn a lot from your post but I still can’t finish the project I want to do simply because I am a newbie for web programming. I need to finish a project to create dynamic table. I have came up a description below for all functions it will need. I am wondering if you do freelance job? Or you can recommend somebody to help me. Or you can provide some help on generating parametric cell values based on values in other cells. Please let me know. Thanks a lot…
    ————————————————-
    Dynamic table creation

    Using mySQL, PHP, html, javascript, ajax, css to create multiple dynamic tables for collecting data, saved to mySQL tables, and retrieving and displaying data from mySQL database based on user’s input. Must have demonstrated experience and capability to do this work. Must be able to provide a logic clear/clean architecture for the design.

    For collecting data input by user, operations on the table will be adding rows or/and columns, depending on user’s action on the web. The value of each cell may be direct input, selecting from dropdown list saved in another mySQL table column, selecting from a calendar table, auto-generated text based on values in other cells, or auto-computed values using values in other values, etc.

    For retrieving and displaying data using table based on the user’s input, some value will be directly from the mySQL table. Some value are to be retrieved from another mySQL table using the filters defined in the current mySQL table. Some cell value may be selecting from dropdown list of column or row values in certain range in a mySQL table, selecting from a calendar table, auto-generated text and/or auto-computed values using values in other cells or those within certain range of one or multiple column/row in a mySQL table

    Formatting the table based on the table areas, like border thickness, background colors, text font type, colors, etc. Delete/Edit button for row/columns. Open/Collapsible display of table area. Use multiple tabs to organize a long table. Use slider to restrict the table area.

    Merge neighboring cells in a column or row if they share the same value.

    Generating XML files based on user’s definition using the data in the table/mySQL database. Incomplete final deliverables include ALL source codes and flowchart(s) showing the process of calling functions/subroutines, etc.

  10. @Jack – Thank you for offering me a business opportunity, but currently I have no free time. I’m involved in several huge projects so I can only help you with advice or maybe guidelines. Your detailed comment will attract attention and someone will contact you for sure. Items of the project sounded feasible. There will be some work on server side (PHP, retrieving data from MySQL database, XML …) and on client side (JavaScript, DOM, AJAX …). So far I didn’t dynamically merge table cells (with JavaScript) but it doesn’t mean there should be a problem. Merging cells in a row is easier to perform than merging cells in a column.

    Hey guys, any comment about Jack’s offer is more than welcome.
    Thanks!

  11. Dear Dbunic,
    I want to insert table rows using JavaScript and can manipulate that table using 4 buttons: ‘add’, ‘delete’, reset and ‘modify’. Three options are working but my problem is this: “to modify table values when we clicked and checked of a checkbox the table row values to be displayed in the form of respected fields”

    I’m really helpless, please help.
    Thanks in advance,
    Govardhana Rao

  12. @Govardhan – It’s possible to modify / append TD content using DOM. As you can see in this post, DIV elements are created and appended to table cells. If you have online example to show, I will help you in resolving functionality of fourth button.

  13. Hi Darko!
    Posting again using PRE rather than CODE, sorry!
    Great stuff here, I must say! Should there be a problem with combining an ‘only xxx_only’ with mandatory cloning?
    My source div: (time is just for styles)

    <!-- with clone - won't go in cell -->
    <div id="time" class="drag clone time">11:00</div>
    
    <!-- without clone - will go in cell -->
    <div id="time" class="drag time">12:00</div>
    

    My target cell:

    <td class="only time_only"></td>
    

    And my javascript (partial):

    rd.only.div.t0700 = 'detail_only';
    

    If I use the ‘clone’ attribute, it breaks my ‘only’ restriction (it won’t go in the cell at all).
    If I take out the ‘clone’ class, the ‘only’ works fine.

    Ideas? Thanks!!

  14. @Steph – Each DIV element should have unique id. In a moment of cloning, REDIPS.drag changes id (suffix is added to the original id). So, it is only needed to append new rule for the cloned element using myhandler_cloned event listener. Here is solution to dynamically append drop rule for cloned elements:

    var redips_init;
    
    // redips initialization
    redips_init = function () {
        // reference to the REDIPS.drag library
        var rd = REDIPS.drag,
            // define "only" class names from first 4 chars of cloned DIV id
            only = {'time': 'time_only',
                    'staf': 'staff_only',
                    'site': 'site_only',
                    'cust': 'customer_only',
                    'acti': 'activity_only',
                    'extr': 'extra_only'};
        // after element is cloned define dropping rule
        rd.myhandler_cloned = function () {
            // define variables
            var cloned_id = rd.obj.id,          // cloned id
                name = cloned_id.substr(0, 4);  // first 4 chars from cloned id
            // dynamically add drop rule for cloned element
            rd.only.div[cloned_id] = only[name];
        };
    }
    
    // add onload event listener
    if (window.addEventListener) {
        window.addEventListener('load', redips_init, false);
    }
    else if (window.attachEvent) {
        window.attachEvent('onload', redips_init);
    }
    
  15. Hi dbunic,
    I am creating a dynamic table which has got a dropdown box by using javascript, the values for dropdown box are populated from MySQL database. I am using AJAX to fetch the contents and creating a XML response as well. So far I am successful in doing this and it is perfectly working fine in IE browser but it is not working in other browsers. Below is my AJAX script and getting problem in getOptions() method inside for loop.

    function getOptions() {
        xmlDoc = getXMLResponse();
        var options = xmlDoc.getElementsByTagName("options")[0];
        var arr = new Array();
        var optionList = new Array(); 
        arr = options.childNodes;
        var i = 0;
        for(; arr[i] != null; i++){
            optionList[i] = arr[i].firstChild.nodeValue;
        }
        return optionList;
    }
    
    function getXMLResponse() {
        var text;
        xmlHttp = getXMLHttpRequest();
        var URL = "getParticulars.action";
        xmlHttp.open('POST', URL, false);
        xmlHttp.send(null);
        text = xmlHttp.responseText;
        xmlDoc = getXMLDoc(text);
        return xmlDoc;
    }
    
    function getXMLDoc(text) {
        if (window.DOMParser) {
            parser=new DOMParser();
            xmlDoc=parser.parseFromString(text,"text/xml");
        }
        // Internet Explorer
        else {
            xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async=false;
            xmlDoc.loadXML(text);
        }
        return xmlDoc;
    }
    
    function getXMLHttpRequest() {
        var xmlHttp;
        try {
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    alert("Your browser does not support AJAX!");
                    return null;
                }
            }
        }
        return xmlHttp;
    }
    
  16. @Farhan – The problem is that you’re trying to get children of a text node. FF and Chrome will have a text node prior to the element node while IE won’t. Here is displayed error from Chrome JavaScript console:

    Uncaught TypeError: Cannot read property 'nodeValue' of null
    

    Your loop should process only element nodes:

    for (; arr[i] != null; i++) {
        // if node is element node (not text node) push value to the Array
        if (arr[i].nodeType === 1) {
            optionList.push(arr[i].firstChild.nodeValue);
        }
    }
    

    I found a nice explanation of DOM nodeType constants in JavaScript.

  17. Hi dbunic,
    I have created a row dynamically using JavaScript and I need to assign name/id for the controls (cells). I’m using Struts 1.2.

    // JavaScript function
    function addRow(tableID) {
        var table = document.getElementById('dataTable'),
            rowCount = table.rows.length,
            row = table.insertRow(rowCount),
            colCount = table.rows[0].cells.length,
            i;
        // for loop
        for (i = 0; i < colCount + 1; i++) {
            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            switch (newcell.childNodes[0].type) {
            case 'text':
                newcell.childNodes[0].value = '';
                break;
            case 'checkbox':
                newcell.childNodes[0].checked = false;
                break;
            case 'select-one':
                newcell.childNodes[0].selectedIndex = 0;
                break;
            }
        }
    }
    
  18. @Ramesh – Setting name/id property to the newly created form element should not be a problem:

    // define reference to the child element
    el = newcell.childNodes[0];
    // set new Name to the form element
    el.name = 'someName';
    // set Id to the referenced element
    el.id = 'someId';
    

    Well, your question was not completely clear to me, so I hope this answer will be fine. If not, please post a comment with more details. Cheers!

  19. Hi dbunic,

    Thanks a lot for your timely help and it really helped me out to move forward.

    Thanks,
    Ramesh/

Leave a Comment