<!DOCTYPE html>
<html>
<head>
<title>Tables</title>
</head>
<body>
<h1>Tables</h1>
<p id="attendOutput"></p>
<table id="infoTable">
<tr><th>First</th><th>Last</th><th>Actions</th></tr>
</table>
<script>
const infoTable = document.getElementById("infoTable");
const attendOutput = document.getElementById("attendOutput");
var people = [
{ first: "Bob", last: "Smith", attendance: 0 },
{ first: "Sarah", last: "Red", attendance: 0 },
];
printTable();
attendOutput.innerHTML = "Attendance : " + countAttendance();
function printTable() {
//loop through people array
for (var i = 0; i < people.length; i++) {
//1 create a new row in table. -1 means at the bottom of table
var row = infoTable.insertRow(-1);
//2 insert each cell starting at far left
row.insertCell(0).innerHTML = people[i].first;
row.insertCell(1).innerHTML = people[i].last;
row.insertCell(2).innerHTML = '<button onclick="attend(this)">Here</button>';
row.insertCell(2).innerHTML = '<button onclick="removeRow(this)">Remove</button>';
}
}
//update the status of attendance for each row
function attend(id) {
var i = parseInt(id.parentNode.parentNode.rowIndex); //get the row number of the table by traversing to the parent
if (people[i - 1].attendance == false) {
infoTable.rows[i].style.background = "yellow";
people[i - 1].attendance = 1; //update the data value
} else {
infoTable.rows[i].style.background = "none";
people[i - 1].attendance = 0; //update the data value
}
console.log(people);
attendOutput.innerHTML = "Attendance : " + countAttendance();
}
//count the number of people who are present
function countAttendance() {
let count = 0;
for (var i = 0; i < people.length; i++) {
if (people[i].attendance == 1) {
count++;
console.log(count);
}
}
return count + " / " + people.length;
}
//remove a row from the table
function removeRow(id) {
var i = id.parentNode.parentNode.rowIndex; //get the row number of the table
infoTable.deleteRow(i); //go to the table and delete the specific row number i
}
//add a new member
function addMember() {
let fnl = ["Sam", "John", "Sally", "Billy"];
let lnl = ["Smith", "Mann", 'High', "Long"]
let fn = fnl[Math.round(Math.random() * fnl.length)];
let ln = lnl[Math.round(Math.random() * fnl.length)];
var person = { first: fn, last: ln, attendance: 0 };
people.push(person); //add the new memeber to the people list
}
//update table with new members
function deleteTable() {
printTable(); //reprint the table
}
</script>
</body>
</html>