Why does this doesn't work for the innerHTML while it works perfectly fine when printing it on console.log()?
const hashTable = document.getElementById("hashTable");
const myString = document.getElementById("typeText");
const hashButton = document.getElementById("hash-btn");
const myArray = [];
// Convert to 32bit integer
function stringToHash(string) {
var hash = 0;
if (string.length == 0) return hash;
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash;
}
return hash;
}
hashButton.addEventListener("click", () => {
const string = myString.value;
myArray.push(string);
myArray.forEach((element) => {
console.log(stringToHash(element), element);
hashTable.innerHTML = `
<tr>
<th scope="row">${stringToHash(element)}</th>
<td>${element}</td>
</tr>
`;
});
});
<body>
<div class="container animate__animated animate__slideInRight">
<!-- Navbar -->
<!-- Navbar -->
<h1 class="mt-5 mb-5 display-2 text-center">Hash Table</h1>
<div class="form-outline">
<input type="text" id="typeText" class="form-control" />
<label class="form-label" for="typeText">String</label>
</div>
<div class="d-grid gap-2 my-4">
<button class="btn btn-primary" id="hash-btn" type="button">
Generate Hash
</button>
</div>
<div class="table-responsive mt-5">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">String</th>
</tr>
</thead>
<tbody id="hashTable"></tbody>
</table>
</div>
</div>
<!-- MDB -->
<script
type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.0.0/mdb.min.js"
></script>
<script src="HashTable.js"></script>
</body>
As you can see, it only generates one tr.
it only generates one tr
No, it generates all of them. Each one is just overwriting the previous one:
hashTable.innerHTML = `
<tr>
<th scope="row">${stringToHash(element)}</th>
<td>${element}</td>
</tr>`;
This sets the entire value of the innerHTML, overwriting whatever was already there. You can append the value instead:
hashTable.innerHTML += `
<tr>
<th scope="row">${stringToHash(element)}</th>
<td>${element}</td>
</tr>`;
Though since your logic re-outputs the entire array, you'll also want to remove all of the output before re-generating it:
hashTable.innerHTML = ''
myArray.forEach((element) => {
console.log(stringToHash(element), element);
hashTable.innerHTML += `
<tr>
<th scope="row">${stringToHash(element)}</th>
<td>${element}</td>
</tr>`;
});