0

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.

6 Answers 6

1

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

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

1 Comment

Thank you, this solved my problem and didn't require much of structural edits to the HTML part. Also this was without jQuery, bless you!
0

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...

Comments

0

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();'/>

Comments

0

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/

Comments

0

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>

Comments

0

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

1 Comment

For me this only did one row with one column. I put in the number '7' and it should've done 7 rows with 7 columns. Otherwise this seems like a good solution, and thanks for the quick fix to the appending "problem" I had!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.