Background: I've been working on nested for loop exercises. The program I'm writing is meant to take column and row data and create a letter matrix or grid using a nested for loop. I was able to get the data to compile in a grid (great!) but there is a line of unnecessary data stuck on top of the grid.(not so great...) Can anyone let me know what could be causing this, I believe it is something extremely simple but my brain is likely fried from looking at this for so long.
Any help would be greatly appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<title>""</title>
<script>
function letter_matrix() {
let column = parseInt(document.form.letter_column.value);
let rows = parseInt(document.form.letter_rows.value);
let text = "<table><th></th>";
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (let i = 0; i < rows ; ++i) {
text += "<tr>"+ letters.charAt(i) + "</td>";
for(let j = 0; j < column ; j++){
let k = (i * rows + j) % 26;
text += "<td>"+letters.charAt(k)+ "</td>";
}
}
text += "</table>";
document.getElementById("results").innerHTML= text;
}
</script>
</head>
<body>
<h1>""</h1>
<form name="form" action = "javascript:letter_matrix();">
Columns: <input type="text" name="letter_column">
Rows: <input type="text" name="letter_rows">
<input type="submit" value="Enter values.">
</form>
<pre id="results">
</pre>
</body>
</html>
In your first for
you create a <tr>
add some text and close a </td>
.
You should most likely just open a tr
and after the inner for
then close the tr
for (let i = 0; i < rows; ++i) {
text += "<tr>";
for (let j = 0; j < column; j++) {
let k = (i * rows + j) % 26;
text += "<td>" + letters.charAt(k) + "</td>";
}
text += '</tr>';
}