简体   繁体   中英

Insert multiple rows and columns to a table in html dynamically using javascript code

I am trying to insert multiple rows and columns to create a table in html dynamically by selecting the number of rows and columns in dropdown list using javascript code like in MS Word. For example if I select number of rows as 5 and number of columns as 5 from the dropdown list of numbers. 5 rows and 5 columns should get displayed.

My question is how can I add multiple rows and columns dynamically to create a table by selecting the number of rows and columns from the drop down list.

Since, <table> element is the one of the most complex structures in HTML, HTML DOM provide new interface HTMLTableElement with special properties and methods for manipulating the layout and presentation of tables in an HTML document.

So, if you want to accomplish expected result using DOM standards you can use something like this:


HTML:

<ul>
    <li>
        <label for="column">Add a Column</label>
        <input type="number" id="column" />
    </li>
    <li>
        <label for="row">Add a Row</label>
        <input type="number" id="row" />
    </li>
    <li>
        <input type="button" value="Generate" id="btnGen" />
        <input type="button" value="Copy to Clipboard" id="copy" />
    </li>
</ul>
<div id="wrap"></div> 

JS new:

JavaScript was improved.

(function (window, document, undefined) {
    "use strict";

    var wrap = document.getElementById("wrap"),
        setColumn = document.getElementById("column"),
        setRow = document.getElementById("row"),
        btnGen = document.getElementById("btnGen"),
        btnCopy = document.getElementById("btnCopy");

    btnGen.addEventListener("click", generateTable);
    btnCopy.addEventListener("click", copyTo);

    function generateTable(e) {
        var newTable = document.createElement("table"),
            tBody = newTable.createTBody(),
            nOfColumns = parseInt(setColumn.value, 10),
            nOfRows = parseInt(setRow.value, 10),
            row = generateRow(nOfColumns);

        newTable.createCaption().appendChild(document.createTextNode("Generated Table"));

        for (var i = 0; i < nOfRows; i++) {
            tBody.appendChild(row.cloneNode(true));
        }

        (wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
    }

    function generateRow(n) {
        var row = document.createElement("tr"),
            text = document.createTextNode("cell");

        for (var i = 0; i < n; i++) {
            row.insertCell().appendChild(text.cloneNode(true));
        }

        return row.cloneNode(true);
    }

    function copyTo(e) {
        prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
    }
}(window, window.document));

JS old:

(function () {
    "use strict";

    var wrap = document.getElementById("wrap"),
        setColumn = document.getElementById("column"),
        setRow = document.getElementById("row"),
        btnGen = document.getElementById("btnGen"),
        copy = document.getElementById("copy"),
        nOfColumns = -1,
        nOfRows = -1;

    btnGen.addEventListener("click", generateTable);
    copy.addEventListener("click", copyTo);

    function generateTable(e) {
        var newTable = document.createElement("table"),
            caption = newTable.createCaption(),
            //tHead = newTable.createTHead(),
            //tFoot = newTable.createTFoot(),
            tBody = newTable.createTBody();

        nOfColumns = parseInt(setColumn.value, 10);
        nOfRows = parseInt(setRow.value, 10);

        caption.appendChild(document.createTextNode("Generated Table"));

        // appendRows(tHead, 1);
        // appendRows(tFoot, 1);
        appendRows(tBody);

        (wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.firstElementChild);
    }

    function appendColumns(tElement, count) {
        var cell = null,
            indexOfRow = [].indexOf.call(tElement.parentNode.rows, tElement) + 1,
            indexOfColumn = -1;

        count = count || nOfColumns;

        for (var i = 0; i < count; i++) {
            cell = tElement.insertCell(i);
            indexOfColumn = [].indexOf.call(tElement.cells, cell) + 1;
            cell.appendChild(document.createTextNode("Cell " + indexOfColumn + "," + indexOfRow));
        }
    }

    function appendRows(tElement, count) {
        var row = null;
        count = count || nOfRows;
        for (var i = 0; i < count; i++) {
            row = tElement.insertRow(i);
            appendColumns(row);
        }
    }

    function copyTo(e) {
        prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
    }
}());  

If you want to copy generated result to clipboard you can look at answer of Jarek Milewski - How to copy to the clipboard in JavaScript?

I had one sample code...try this and modify it according to your requirement. May it helps you out.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Untitled Document</title>
        <style type="text/css">
            #mytab td{
                width:100px;
                height:20px;
                background:#cccccc;
            }
        </style>
        <script type="text/javascript">
            function addRow(){
                var root=document.getElementById('mytab').getElementsByTagName('tbody')[0];
                var rows=root.getElementsByTagName('tr');
                var clone=cloneEl(rows[rows.length-1]);
                root.appendChild(clone);
            }
            function addColumn(){
                var rows=document.getElementById('mytab').getElementsByTagName('tr'), i=0, r, c, clone;
                while(r=rows[i++]){
                    c=r.getElementsByTagName('td');
                    clone=cloneEl(c[c.length-1]);
                    c[0].parentNode.appendChild(clone);
                }
            }
            function cloneEl(el){
                var clo=el.cloneNode(true);
                return clo;
            }
        </script>

    </head>
    <body>
        <form action="">
            <input type="button" value="Add a Row" onclick="addRow()">
            <input type="button" value="Add a Column" onclick="addColumn()">
        </form>
        <br>

        <table id="mytab" border="1" cellspacing="0" cellpadding="0">
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </body>
</html>

Instead of button , you can use select menu and pass the value to variable. It will create row ,column as per the value.

Try something like this:

var
    tds = '<td>Data'.repeat(col_cnt),
    trs = ('<tr>'+tds).repeat(row_cnt),
    table = '<table>' + trs + '</table>;

Then place the table in your container:

document.getElementById('tablePreviewArea').innerHTML = table;

Or with JQuery:

$('#tablePreviewArea').html(table);

Here is the JSFiddle using native js . Here is the JSFiddle using jQuery .

About the string repeat function

I got the repeat function from here :

String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}

You can use this function to generate dynamic table with no of rows and cols you want:

function createTable() {
    var a, b, tableEle, rowEle, colEle;
    var myTableDiv = document.getElementById("DynamicTable");
    a = document.getElementById('txtRows').value; //No of rows you want
    b = document.getElementById('txtColumns').value; //No of column you want

    if (a == "" || b == "") {
        alert("Please enter some numeric value");
    } else {
        tableEle = document.createElement('table');
        for (var i = 0; i < a; i++) {
            rowEle = document.createElement('tr');

            for (var j = 0; j < b; j++) {
                colEle = document.createElement('td');
                rowEle.appendChild(colEle);
            }
            tableEle.appendChild(rowEle);
        }
        $(myTableDiv).html(tableEle);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM