0

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.

2
  • 3
    So what's your question? Commented Jan 23, 2014 at 6:37
  • jQuery is fine or u only need javascript Commented Jan 23, 2014 at 6:39

5 Answers 5

2

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

$(myTableDiv).html(tableEle); - is this jQuery?
So the whole library must be included for just one line of code?
If you are not using jQuery then you can do it by javascript. myTableDiv.innerHTML = tableEle.
Not exactly, myTableDiv.innerHTML = tableEle.outerHTML will do.
1

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

2 Comments

Is jQuery really needed for this?
Not a bad point, thx Pavlo. I added the snipped without jquery.
1

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.

5 Comments

Thank you very much.It helped me a lot.Thanks Once again.
@user3188826, If it solves your problem then accept the answer whenever you can.
@Pavlo This answer is not related to meta tag here , i don't know why -1 here. It helped the guy who is asking. If you want info regarding met tag then go to link htmldog.com/guides/html/intermediate/metatags
Besides the meta tag, the code is messy and there is no explanation was was done.
The code is easy to understand without explanation, maybe the new formatted code help to see it clearly
0

The solutions already posted seem overly complex. All you need is:

// I'm assuming the <table> statement is already in the document.
let table=document.getElementById("mytable")
for (let x=0;x<wantrows;++x) {
  let row=table.insertRow(-1)
  for (let y=0;y<wantcols;++y) {
    row.insertCol(-1)
  }
}

I'm not showing the code to get the number of rows and columns from form inputs. That wasn't the question, no point cluttering up an answer with irrelevant information.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.