0

I want to save the value of the input into the local storage upon button click.

allNames = []

function submit() {
  let names = document.getElementById("names").value;
  allNames.push(names);

  localStorage.setItem("totalNames", JSON.stringify(allNames))
  console.log(JSON.parse(localStorage.getItem("totalNames")))

}
<button onclick="submit()">Submit</button>

<input id="names" placeholder="Enter Name">

I want to save the value of the name the user enters into the input to local storage so even after the page refreshes, the name will be saved.

2
  • 1
    what isnt working? Commented Apr 2, 2020 at 17:05
  • Every time I refresh the page, the local storage is cleared Commented Apr 2, 2020 at 17:05

1 Answer 1

3

You are re-initialing the array every time and then saving into the LS;instead

you should check if there is previuos value in LS and assign to allnames if exist like this

let allNames;

if(localStorage.getItem("totalNames")){
 allNames = JSON.parse(localStorage.getItem("totalNames"))
}else{
 allNames= []
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.