2

I have tried several times to get this to work, I am making a leaderboard with a text function input that sets the local storage values. I can not get it to work with making my key an array ,so that i can have multiple values to the same key.

var userName = document.getElementById('navn');
var userAvg = document.getElementById('avg');
var userAmount = document.getElementById('amount');


function addData() {
    localStorage.setItem('userName', userName.value);
    localStorage.setItem('userAvg', userAvg.value);
    localStorage.setItem('userAmount', userAmount.value);
    var table = document.getElementById("myTable");
    var row = table.insertRow(4);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    cell1.innerHTML = navn.value;
    cell2.innerHTML = avg.value;
    cell3.innerHTML = amount.value;
}
<html>
  <div id="board">
      <ul id="list"></ul>
      <br/> Navn
      <input type="text" id="navn" />
      <br/> Gennemsnitlig Promille
      <input type="text" id="avg" />
      <br/> Antal genstande i alt
      <input type="text" id="amount" />
      <br/>
      <br/>
      <button type="button" onclick="addData()">Tilføj Data </button>
      <table id="myTable">
          <tr>
              <th onclick="sortTable(0)">Navn</th>
              <th onclick="sortTable(1)">Gennemsnitlig Promille</th>
              <th onclick="sortTable(2)">Antal Genstande i alt</th>
          </tr>
      </table>
  </div>
</html>
phwt
  • 1,356
  • 1
  • 22
  • 42
Adam Klint
  • 21
  • 2

1 Answers1

2

When you store an array in local storage you need to stringify it and when getting from local storage you need to parse JSON again.

Here's an example:

//saving to local storage
localStorage.setItem("userName", JSON.stringify(userName.value));

//reading from local storage
var userName = JSON.parse(localStorage.getItem("userName"));

In your case you could create an object like this:

let user = {
    userName: "...",
    userAvg: "...",
    userAmount: "..."
}

Save it with localStorage.setItem("user", JSON.stringify(user)).

Retrieve its content with user = JSON.parse(localStorage.getItem("user")).

Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31