Pepelius
Pepelius

Reputation: 1609

Generate a HTML table from a given number with JavaScript

I previously came up with a situation that solved my problem in generating the table from a given word and printing it diagonally.

This time however, I need to generate a table using JavaScript (no jQuery or other alternatives) from given numeric value. The given value determines the number of cols and rows (always equal amount).

Example: I'd give a number 8 to my text-input, the JavaScript generates a table with 8 cols and 8 rows.

The value needs to be numeric, so the run should break if the given value isNaN.

Here is the previous code I tried to modify in order to make this happen, but failed with it pretty miserably:

function generateTable() {
  var $c = document.getElementById("container");
  var $table = document.createElement('table');
  var $tbody = document.createElement('tbody');
  var word = document.getElementById('word').value.split("");
  $c.appendChild($table);
  $table.appendChild($tbody);
  for (var i=0, l=word.length; i<l; i++) {
    var $tr = document.createElement('tr');
    $tbody.appendChild($tr);
    for (var j=0, jl=word.length; j<jl; j++) {
      var $td = document.createElement('td');
      $td.appendChild(document.createTextNode(i==j ? word[i] : "-"));
      $tr.appendChild($td);
    } 
  }
}
<textarea id="word"></textarea><br>
<button id="generate" onclick="generateTable();">Generate</button>
<div id="container"></div>

Yes, that handles the given word and prints it diagonally, I tried to change some values and make an effect on how this generates the table, but managed to break the whole thing pretty much. That's why instead of posting the code I modified, I'm posting the code where I started to modify this from.

Upvotes: 0

Views: 2101

Answers (6)

Rohit Rehan
Rohit Rehan

Reputation: 570

This code should solve your problem

function generateTable() {
  var $c = document.getElementById("container");
  var $table = document.createElement('table');
  var $tbody = document.createElement('tbody');
  if(isNaN(document.getElementById('word').value)) return;
  var l = parseInt(document.getElementById('word').value);
  $c.appendChild($table);
  $table.appendChild($tbody);
  for (var i=0; i < l; i++) {
    var $tr = document.createElement('tr');
    $tbody.appendChild($tr);
    for (var j=0;  j < l; j++) {
      var $td = document.createElement('td');
      $td.appendChild(document.createTextNode(i==j ? l : "-"));
      $tr.appendChild($td);
    } 
  }
}

here is the working demo

If you want the table to replace every time the prevoiusly you should empty the container before appending the new table.

use

$c.innerHTML="";

before

$c.appendChild($table);

Upvotes: 0

jdphenix
jdphenix

Reputation: 15415

You can just run two inner loops, appending rows and cells as appropriate based on the input.

var input = document.getElementById('input'),
  output = document.getElementById('output'),
  btnGen = document.getElementById('btnGen');

btnGen.addEventListener('click', function() {
  var table;
  output.innerHTML = '';

  if (table = generateTable(input.value)) {
    output.appendChild(table);
  } else {
    output.textContent = 'Invalid user input';
  }
});

function generateTable(n) {
  if (typeof n !== 'number' && isNaN(n) || +n === 0) {
    return false;
  }

  var table = document.createElement('table'),
    size = +n;

  for (var i = 0; i < n; i++) {
    var tr = document.createElement('tr');
    for (var j = 0; j < n; j++) {
      var td = document.createElement('td');
      td.textContent = i + "," + j
      tr.appendChild(td);
    }
    table.appendChild(tr);
  }
  output.appendChild(table);
  return table;
}
<input id="input"></input>
<button id="btnGen">Generate</button>
<div id="output"></div>

Upvotes: 0

janatuerlich
janatuerlich

Reputation: 173

This is what I came up with, without jQuery:

HTML:

<h3>Create your table!</h3>
<input type="text" id="trc" />
<button id="create">Create</button>
<div id="table"></div>

JavaScript:

document.getElementById("create").onclick=function() {
    var trtd = document.getElementById("trc").value;
    if(isNaN(trtd) || trtd < 1) {
        document.getElementById("table").innerHTML = "The given value must be a number!";
    }
    else {
        var table = "<table>";
        for(i = 0; i < trtd; i++) {
            table += "<tr>";
            for(j = 0; j < trtd; j++) {
                table += "<td>Cell</td>";
            }
            table += "</tr>";
        }
        table += "</table>";
        document.getElementById("table").innerHTML = table;
    }
}

You can fill the Cells with any value you like.

See Fiddle

Upvotes: 1

Gereltod
Gereltod

Reputation: 2234

I'm not sure my answer is good enough or not. My English sucks, maybe I understood your question wrong.

html:

<div id="container">
    <input type="text" id="num_input" />
    <input type="button" id="generator" value="press on me">

    <div id="table_container"></div>
</div>

js:

$(function(){

    $("#generator").click(function(){

        val = $("#num_input").val();
        if(!isNaN(val)){

            $("#table_container").html("");
            $("#table_container").append("<table>");

            for (i=0; i<val; i++) {
                $("#table_container table").append("<tr id='"+i+"'>");

                for (j=0; j<val; j++){
                    $("#table_container tr#"+i).append("<td>"+i+"-"+j+"</td>");
                }
                $("#table_container").append("</tr>");
            }
            $("#table_container").append("</table>");
        }
    })    
})

Working link: http://jsfiddle.net/thisizmonster/jgf25ach/

Upvotes: 0

Tushar Gupta
Tushar Gupta

Reputation: 15913

You can do just this

function createTable()
{
    var num_rows = document.getElementById('int').value;
    var num_cols = num_rows;
    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 style="width:30px;height:20px">';
            tbody += '</td>'
        }
        tbody += '</tr>\n';
    }
    var tfooter = '</table>';
    document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
<label>Integer: <input type="text" name="rows" id="int"/></label><br />
<div id="wrapper"></div>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>

Upvotes: 0

stambikk
stambikk

Reputation: 1365

Seems simple enough, just replace the l = word.length in your for loop for the actual value that is given in the text area...There is a plenty of questions here on stackoverflow that deal with validating numbers in javascript...

Upvotes: 0

Related Questions