ali ali - 4 months ago 9
HTML Question

Generate Number of Column and Number of Rows on user input

How can I generate a table with number of columns and rows from user input?

I want to offer two input fields to the user for row and column numbers to create the table on a button click.

Answer

you can do it using a for loop for example

function createTable(r, c) {

  var tb = document.createElement('table');

  for (var i = 0; i < r; i++) {
    var row = document.createElement('tr');
    for (var j = 0; j < c; j++) {
      var column = document.createElement('td');
      column.appendChild(document.createTextNode(" row:"+i + " column:"+j));
      row.appendChild(column);
    }
    tb.appendChild(row);
  }

  return tb;
}

here's a working fiddle https://jsfiddle.net/c6k9foeb/

[EDIT] fiddle with inputs https://jsfiddle.net/c6k9foeb/1/

[EDIT2] fiddle with text inputs on cells https://jsfiddle.net/c6k9foeb/2/