stofu
stofu

Reputation: 118

value from localstorage is not getting saved on screen

i have created a simple textbox app in js, in the app when i enter a value it get saved temporarily, but i want to save it permanently. i have use local-storage but its not working to my liking.

here is the JavaScript part

function addValue(){
  let ad = document.getElementById("u");
  let newli = document.createElement("li");

  newli.textContent = document.getElementById("box3").value;

  document.getElementById("box3").value = " ";
   let local = ad.appendChild(newli);
  localStorage.setItem('name',local.textContent);
  

}

here is the html part

<ul id="u">
        <li>task1 </li>
        <li> task 2 </li>
        <li> task 3</li>
    </ul>

    <input type="text" id= "box3">

    <input type="button" value="add " onclick="addValue()">

Upvotes: 3

Views: 1786

Answers (2)

Freduah Gideon
Freduah Gideon

Reputation: 1350

In Respect To The Problem You Stated In The Comments.

Firstly We Have To Call The Onload Function Of The Document. This function is called anytime the document is loaded and thus is the right function to use for this project.

PS: I assumed you are familiar with arrow functions that's why i used them. let me know if it looks confusing to you

document.onload = (()=>{
  // NB: IN ORDER FOR THIS CODE TO WORK MAKE SURE IT APPEARS AT THE BOTTOM OF THE HTML PAGE
 // We get the elements from the localStorage and parse it into an array since it is a string at this stage
 const items = JSON.parse(localStorage.getItem("name"))
// We select the parent element we want to append the items to
const parentUlToAppendTo = document.querySelector("#u")

// We use the map functions with template literals i.e (``) to return HTMLElements with the items as their innerHTML
const listItems = () => items.map(item => `<li>${item}</li>`)
// We Append The Elements To The parentUlToAppendTo Element
parentUlToAppendTo.insertAdjacentHTML("afterbegin",listItems())

})()
``

Upvotes: 0

Freduah Gideon
Freduah Gideon

Reputation: 1350

You need to store the data in an array instead.

saving it like this localStorage.setItem('name',local.textContent); overwrites the content replacing it with a new value.

Using an array you can append the new content instead of overwriting it.

Use this code

    var storage = localStorage.getItem("name");
    if (storage) {
      var storageContent = JSON.parse(localStorage.getItem("name"));
      storageContent.push(newli.textContent);
      localStorage.setItem("name", JSON.stringify(storageContent));
    } else {
      localStorage.setItem("name", JSON.stringify([newli.textContent]));
    }

Upvotes: 3

Related Questions