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.