Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading