Home > Blockchain >  How do I make a website save what we type into an input box using localStorage?
How do I make a website save what we type into an input box using localStorage?

Time:05-17

So here’s the concept:

I’m making a simple website where there’s an input box, and the website will save what we type onto localStorage, and show it up onto the website body. We can change the text in the input box anytime, and the site will automatically update.

Expected Result
Typing in the input box will update the site

Actual Result
Nothing happens


Here’s the code:

<h1>localStorage Test</h1>

<form>
  <label for="name">Your Name:</label><br>
  <input type="text" id="name" name="name"><br>
  <button onclick="saveName()" type="button">Save Name</button>
</form>

<br>

<p id="output"> </p>

<script>
  document.getElementById("output").value = localStorage.getItem("name");
  
  function saveName() {
    var name = document.getElementById("name");
    localStorage.setItem("name", name.value);
  }
</script>

Thanks in advance.

CodePudding user response:

I think you have two issues.

The first one is that you do not update the element after you set the localstorage. This can be done by putting the code in a function and call for the function after you update the value.

Second, to display text inside a <p> tag you need to use innerHTML or preferably innerText.

See example code below

function getName() {
    document.getElementById("output").innerText = localStorage.getItem("name");
}
getName();

function saveName() {
    var name = document.getElementById("name");
    localStorage.setItem("name", name.value);
    getName();
}

CodePudding user response:

You are not updating the given name on the screen, you are just updating it in the localStorage. You need to write as follow:

<h1>localStorage Test</h1>
<form>
  <label for="name">Your Name:</label><br>
  <input type="text" id="name" name="name"><br>
  <button onclick="saveName()" type="button">Save Name</button>
</form>

<br>

<p id="output"> </p>

<script>
  function setName(name){
    document.getElementById("output").textContent = name;
  }

  let currentNameInStoarge = localStorage.getItem("name");
  if(currentNameInStoarge !== null) setName(currentNameInStoarge);
  
  function saveName() {
    var name = document.getElementById("name");
    localStorage.setItem("name", name.value);
    setName(name.value);
  }
</script>

I also added a check in the beginning to check if the localStorage has the "name" property at all.
And as @David said, there is no "value" property to <p> element so I changed it to be textContent.

  • Related