Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  186] [ 2]  / answers: 1 / hits: 30368  / 6 Years ago, sun, october 21, 2018, 12:00:00

How can I populate a table with JavaScript in the proper way?




function loadTableData() {

//0: Date
//1: Name

var row = document.getElementById(test);

var x = row.insertCell(0);
x.innerHTML = 10/17/2018;

var x = row.insertCell(1);
x.innerHTML = john doe;

}

<table id=myTable class=table table-borderless table-striped table-earning>
<thead>
<tr>
<th>date</th>
<th>file name</th>
</tr>
</thead>
<tbody>
<tr id=test></tr>
</tbody>
</table>
<script>loadTableData();</script>




My current code populates the first two cells but I would like to move to the next column and populate another two cells. Im not sure how to do this the correct way.


Current output
enter


More From » html

 Answers
87

The trick is to loop over your data and use insertRow to create a row before you insert the data. You can see that the tbody element is empty in this example and each tr element is created dynamically.





<table id=myTable class=table table-borderless table-striped table-earning>
<thead>
<tr>
<th>date</th>
<th>file name</th>
</tr>
</thead>
<tbody id=testBody></tbody>
</table>
<script>
const items1 = [
{ date: 10/17/2018, name: john doe },
{ date: 10/18/2018, name: jane doe },
];
const items2 = [
{ date: 10/17/2019, name: john doe },
{ date: 10/18/2019, name: jane doe },
];
function loadTableData(items) {
const table = document.getElementById(testBody);
items.forEach( item => {
let row = table.insertRow();
let date = row.insertCell(0);
date.innerHTML = item.date;
let name = row.insertCell(1);
name.innerHTML = item.name;
});
}
loadTableData(items1);
loadTableData(items2);
loadTableData([]);
</script>




[#53277] Wednesday, October 17, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradenc

Total Points: 75
Total Questions: 96
Total Answers: 129

Location: Burundi
Member since Thu, Feb 10, 2022
2 Years ago
;