Home > Software engineering >  Generating Hash JavaScript and HTML. Problems with innerHTML
Generating Hash JavaScript and HTML. Problems with innerHTML

Time:05-11

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 >
      <!-- Navbar -->
      <!-- Navbar -->
      <h1 >Hash Table</h1>
      <div >
        <input type="text" id="typeText"  />
        <label  for="typeText">String</label>
      </div>
      <div >
        <button  id="hash-btn" type="button">
          Generate Hash
        </button>
      </div>
      <div >
        <table >
          <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.

CodePudding user response:

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>`;
});
  • Related