Skip to content Skip to sidebar Skip to footer

Dynamically Creating An Html Table With Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got t

Solution 1:

Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.

functioncreateTable()
{
    var num_ports = document.getElementById('ports').value;
    var num_super = document.getElementById('super').value;
    var num_rows = document.getElementById('rows').value;
    var num_cols = document.getElementById('cols').value;
    var tbody = '';
    var colStart = num_cols / num_super;
    for( var i=0; i<num_super; i++){
        var theader = '<div><table border="1">\n';
            for($u=1; $u<=num_rows; $u++){
              tbody += '<tr>';
                for( var j=0; j<colStart; j++)
                {
                tbody += '<td>';
                tbody += 'Cell ' + i + ',' + j;
                tbody += '</td>'
                }
        tbody += '</tr>\n';
    }
    var tfooter = '</table></div>';
    document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}

Solution 2:

var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
  document.write("<tr>");
  for(y = table[x].length;y > 0;y--) {
    document.write("<td>"+y+"</td>");
  }
document.write("</tr>");
}

Sorry if the syntax is wrong. You get the idea.

Solution 3:

You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".

here's the corrected js.

functioncreateTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
    var theader = '<div><table border="1">\n';
    for ($u = 1; $u <= num_rows; $u++) {
        tbody += '<tr>';
        for (var j = 0; j < colStart; j++) {
            tbody += '<td>';
            tbody += 'Cell ' + i + ',' + j;
            tbody += '</td>';
        }
    }
    tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;

}

Post a Comment for "Dynamically Creating An Html Table With Javascript"