I have a form input field where I enter data.
The entered data is then displayed in a table as a new row, with the most recent entry at the top.
What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over the table, I want it to expand and display all hidden rows. Once I move the cursor away, I want the table to collapse again, showing only the latest row.
I've been trying to implement this feature, but every attempt seems to make it worse, and currently, no new rows are being displayed for some reason.
Thank you in advance for any help!
Here is the code snippet:
HTML:
<body>
<div class="container">
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<form>
<label for="fName">Name</label><br />
<input type="text" id="fName" name="fName" /><br />
<input type="submit" id="submitBtn" />
</form>
</div>
CSS:
table {
color: black;
width: 200px;
border-collapse: collapse;
left: 100px;
z-index: 1;
position: absolute;
box-shadow: 0px 2px 5px black;
}
.expand{
display: table-row !important;
}
.collapse{
display: none;
}
tr:not(:first-child){
display: none;
}
JS:
"use strict";
let inputBox = document.querySelector("#fName");
let tBody = document.querySelector("tbody");
const table = document.querySelector('table');
function addRow() {
let row = tBody.insertRow(0);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = inputBox.value;
cell2.innerHTML = "text2";
inputBox.value = " ";
row.classList.add('tr');
}
tBody.classList.add('collapse');
document.querySelector("#submitBtn").addEventListener("click", function (event) {
event.preventDefault();
addRow();
});
// Expand/collapse event listeners:
table.addEventListener('mouseover', function(){
tBody.classList.remove('collapse');
tBody.classList.add('expand');
})
table.addEventListener('mouseout', function(){
tBody.classList.remove('expand');
tBody.classList.add('collapse');
})