I'd like to to populate a Bootstrap table from an array of objects using pure JavaScript.
Here is my data.js file:
JavaScript
let testData = [
{
id : 1,
firstName : 'John',
lastName : 'Smith',
age : 35,
retired : false
},
{
id : 2,
firstName : 'Mary',
lastName : 'Williams',
age : 27,
retired : false
},
{
id : 3,
firstName : 'Bill',
lastName : 'Jones',
age : 83,
retired : true
},
{
id : 4,
firstName : 'Sally',
lastName : 'Lee',
age : 49,
retired : false
}
]
In my main.js file, I have the following function that builds the HTML and populates the table with only the firstName, lastName, and age. But, this function is not working.
function createTable(data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].firstName + "</td>");
tr.append("<td>" + data[i].lastName + "</td>");
tr.append("<td>" + data[i].age + "</td>");
}end(tr);
}
createTable(testData)
Here is my index.html file:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<div id="content-1"></div>
<table class="table">
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Age</th>
</tr>
</thead>
</table>
<tbody>
<!-- what goes here? -->
</tbody>
<script src="./js/data.js"></script>
<script src="./js/main.js"></script>
</body>
</html>
Any assistance would be most appreciated!
Thanks!