0

I'm creating something similar to a to-do-list project, but whenever I refresh the page I lose all the added items, I've tried using:

`

  window.onbeforeunload = function () {
    localStorage.setItem("list", $("#listItem").val());
  };

  window.onload = function () {
    var name = localStorage.getItem("list");
    if (name !== null) $("#listItem").val("list");
  };

`

but still it doesn't work, I may have used it in the wrong place or wrong way. any help please? here is my full code:

HTML: `

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <title>To Do List</title>
  </head>
  <body>
    <section class="section-center">
      <form class="todolist-form">
        <h3>To Do List!</h3>

        <div class="input-button">
          <input type="text" id="items-input" placeholder="e.g. eggs" />
          <input
            type="button"
            class="submit-btn"
            onclick="addItems()"
            value="Submit"
          />
        </div>

        <div class="added-items">
          <ul id="faves"></ul>
        </div>
      </form>
    </section>

    <script src="main.js"></script>
  </body>
</html>

`

Javascript:

`

function addItems() {
  var li = document.createElement("LI");
  li.setAttribute("id", "listItem");

  var input = document.getElementById("items-input");
  li.innerHTML = input.value;
  input.value = "";
  document.getElementById("faves").appendChild(li);

  var deleteBtn = document.createElement("button");
  deleteBtn.classList.add("delete-btn");
  deleteBtn.innerHTML = "Delete";
  deleteBtn.type = "button";
  document.getElementById("faves").appendChild(deleteBtn);

  var hrzBreak = document.createElement("br");
  document.getElementById("faves").appendChild(hrzBreak);

  /*********/


  window.onbeforeunload = function () {
    localStorage.setItem("list", $("#listItem").val());
  };

  window.onload = function () {
    var name = localStorage.getItem("list");
    if (name !== null) $("#listItem").val("list");
  };
}

`

What am I doing wrong? I've included jQuery's CDN too, but still it doesn't work.

  • 1
    trying to focus on the localStorage aspect alone.. did you try to just make something very basic like `localStorage.setItem('key', 'value')` and `console.log( localStorage.getItem('key') )`? You may have those 2 actions called by two different buttons in the same page. Try to see what happens when pressing the first one and then the second one.. reload the page and press again the second one. Consider that `localStorage` is bound to the page origin – Diego D Dec 23 '22 at 10:32
  • @DiegoD Yes it works, I pressed the first button, then the second one i got the console.log, then i refreshed and pressed the second one alone and got the console.log too – Fadi aljohari Dec 23 '22 at 10:40
  • @seriously The id is added through JavaScript for added list items – Fadi aljohari Dec 23 '22 at 10:40
  • @Fadi aljohari Be aware to put calls with `localStorage` in `try-catch` due to private-browsing and or network restrictions like citrix. – Lain Dec 23 '22 at 10:42

3 Answers3

0

Try adding event listeners once and outside of your function


window.onbeforeunload = function () {
  localStorage.setItem("list", $("#listItem").val());
};

window.onload = function () {
  var name = localStorage.getItem("list");
  if (name !== null) $("#listItem").val("list")  
};

function addItems() {
...
}

Amir Sarfar
  • 153
  • 2
  • 11
0
    var texts = [];
function addItems() {
    var input = document.getElementById("items-input");
    createElement(input.value)
    input.value = "";
}

function createElement(value) {
    var li = document.createElement("LI");
    li.setAttribute("id", "listItem");
    li.innerHTML = value;

    document.getElementById("faves").appendChild(li);

    var deleteBtn = document.createElement("button");
    deleteBtn.classList.add("delete-btn");
    deleteBtn.innerHTML = "Delete";
    deleteBtn.type = "button";
    document.getElementById("faves").appendChild(deleteBtn);

    var hrzBreak = document.createElement("br");
    document.getElementById("faves").appendChild(hrzBreak);

    texts.push(value)

}

window.onbeforeunload = function () {
    // Store text array in storage
    localStorage.setItem("list", JSON.stringify(texts));
};

window.onload = function () {
    // get list grom storage
    var list = localStorage.getItem("list");
    if (list !== null) {
        list = JSON.parse(list)
        for (let index = 0; index < list.length; index++) {
            const element = list[index];
            // create your dom element
            createElement(element)
        }
    }
};

Using an Array to manage the data flow. This will do the job but still a mess.

-1

Assuming that $("#listItem").val() will return the data you want, place below block outsite of the addItems() function

window.onbeforeunload = function () {
    localStorage.setItem("list", $("#listItem").val());
  };

window.onload = function () {
    var name = localStorage.getItem("list");
    if (name !== null) $("#listItem").val("list");
};
  • yah this code has several bugs, seems copy paste form somewhere – Nishan Nilupul Dec 23 '22 at 10:43
  • @Lain what do you mean with a part of a bigger code block? this is literally my whole code, i didnt include the CSS tho. how can i make the structure not a mess? I'm still trying to learn :) – Fadi aljohari Dec 23 '22 at 10:44
  • Btw i have tried placing it outside my function, but it still doesn't work, but as a code, it should work right? – Fadi aljohari Dec 23 '22 at 10:48
  • Ok, First place the above block outside the addItems(). Then #listItem not even exists in the HTML, you have to fix that (best thing to do is assign values to an array and use it to populate the DOM and also set to the local storage (https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage) – Nishan Nilupul Dec 23 '22 at 10:50
  • Just a quick question, the #listItem is created through my javascript code, because the list items are created from the javascript too, is that a problem? should my #listItem be created in the HTML? even if i created it from the javascript? Thank you :) – Fadi aljohari Dec 23 '22 at 10:51