Adding table rows and columns in JavaScript

More...

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);
        }
    }
}

This entry was posted on May 8, 2009 and is filed under JavaScript

Related posts

29 Responses to Adding table rows and columns in JavaScript

  1. pervez mohammad says:

    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. S Valencia says:

    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. dbunic says:

    @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. Jack says:

    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. dbunic says:

    @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 says:

    how to get the colums to another table and insert the colums in using table

  7. dbunic says:

    @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.

  8. selva says:

    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

  9. dbunic says:

    @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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>