Issue
I am trying to create a table where each cell consists of a letter and a number. see an image of the target table:
Here is the HTML code that I am using. It's a simple button that when clicked, should call the populateTable()
function and then display the table on the page.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Document</title>
<style>
table { border-collapse: collapse; margin: 1em 0; }
td { border: 1px solid black; padding: 0.3em; }
</style>
</head>
<body>
<h2>Table</h2>
<table id="the-table"></table>
<button type="button" onclick="populateTable();">Populate table</button>
<script src="table.js"></script>
</body>
</html>
But the main issue here is my JS code.
function populateTable(){
letters = ["a", "b", "c", "d", "e"]
numbers = ["1", "2", "3", "4", "5"]
for(let i = 0; i < numbers.length; i++){
document.getElementById("the-table").innerHTML += "<tr>"
for(let j = 0; j < letters.length; j++){
document.getElementById("the-table").innerHTML += "<td>" + letters[j] + numbers[i] + "</td>"
}
document.getElementById("the-table").innerHTML += "</tr>"
}
}
How can I create a new <tr> after inner loop exits?
The outcome of this current code looks like this
Please help :'D
I tried moving around the
document.getElementById("the-table").innerHTML += "<tr>"
and
document.getElementById("the-table").innerHTML += "</tr>"
but to no avail. I tried looking for an answer online, but I found nothing that is useful to my case. things like appendChild were not really what i am looking for exactly. I just want to know why these lines mentioned above ("<tr>") won't work and what's the easiest way to fix this?
Solution
The issue here is that everytime you call += on the table element it creates a new tbody. So all the TDs will show up on a new line. You need to create a variable and create the entire inner table structure and then add it to your table like so. If you inspect the elements after running your code you can see all the tbodies. I hope this helps.
It should be noted, this is not the "proper" way to do this. I'm just providing the fix for the method you chose, as that's how people learn and grow :)
function populateTable(){
letters = ["a", "b", "c", "d", "e"]
numbers = ["1", "2", "3", "4", "5"]
innerTable = '';
for(let i = 0; i < numbers.length; i++){
innerTable += "<tr>"
for(let j = 0; j < letters.length; j++){
innerTable += "<td>" + letters[j] + numbers[i] + "</td>"
}
innerTable += "</tr>"
}
document.getElementById("the-table").innerHTML += innerTable;
}
Answered By - Gauge
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.