Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating table with user input

Tags:

javascript

I'm currently trying to dynamically create a table using JS and HTML.

But at the moment it cannot seem to retrieve the values from user entry.

What I am I doing wrong?

Thanks in advance!

<script type="text/javascript">
function createTable(num_rows, numcols)
{
    var num_rows = document.tablegen.rows.value;
    var num_cols = document.tablegen.cols.value;
    var theader = '<table>\n';
    var tbody = '';

    for( var i=0; i<num_rows;i++)
    {
        // create each row
        tbody += '<tr>';

    for( var j=0; j<num_cols;j++)
    {
        // create cell
        tbody += '<td>';
        tbody += 'Cell ' + i + ',' + j;
        tbody += '</td>'
    }

    // closing row table
    tbody += '</tr>\n';

    }

    var tfooter = '</table>';

    // TO DO

    return theader + tbody + tfooter;
}
</script>
</head>

<body>
<form name="tablegen">
<label>Rows: <input type="text" name="rows"/></label><br />
<label>Cols: <input type="text" name="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<script type="text/javascript">
document.write(createTable());
</script>
like image 880
methuselah Avatar asked Nov 18 '11 12:11

methuselah


2 Answers

I would not recommend to use document.write. read this

Why is document.write considered a "bad practice"?

Try this:

<script type="text/javascript">
function createTable()
{
    var num_rows = document.getElementById('rows').value;
    var num_cols = document.getElementById('cols').value;
    var theader = '<table border="1">\n';
    var tbody = '';

    for( var i=0; i<num_rows;i++)
    {
        tbody += '<tr>';
        for( var j=0; j<num_cols;j++)
        {
            tbody += '<td>';
            tbody += 'Cell ' + i + ',' + j;
            tbody += '</td>'
        }
        tbody += '</tr>\n';
    }
    var tfooter = '</table>';
    document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>

<body>
<form name="tablegen">
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Cols: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>

<div id="wrapper"></div>

You can also use the insertRow and insertCell.

read more:

https://developer.mozilla.org/en/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces

http://www.w3schools.com/js/tryit.asp?filename=try_dom_table_insertrow

like image 192
Book Of Zeus Avatar answered Nov 16 '22 18:11

Book Of Zeus


Instead of return in your function you need to paste table to the document try to write something like this:

instead:

return theader + tbody + tfooter;

write

document.write(theader + tbody + tfooter)
like image 1
antyrat Avatar answered Nov 16 '22 18:11

antyrat