Search code examples
javascriptlocal-storagetextinput

Save Input Value to Local Storage and Retrieve it on a different Page


I have a webpage with 3 different pages: page1, page2 and page3. On the first page, the user will type his name in a textbox. I want to store that value to local storage to use again on page2 and page3.

I cannot even retrieve it on page1. Am I doing something wrong? And I have no idea how to retrieve it on a different page. Any help?

function myFunction() {
var name = document.getElementById("myInput").value;
document.getElementById("greeting").innerHTML = "Hello, " + name + "! Welcome!";
}

localStorage.setItem("userName", name);
document.getElementById("storedName").innerHTML = localStorage.getItem("userName");
<p>What is your name?</p>

<input id="myInput" type="text" placeholder="Name Surname">

<button onclick="myFunction()">Answer</button>

<p id="greeting"></p>
<p id="storedName"></p>


Solution

  • You just have to make a few changes:

    function getName() {
      return localStorage.getItem("userName");
    }
    
    function updateHTML() {
      var name = getName();
      document.getElementById("greeting").innerHTML = "Hello, " + name + "! Welcome!";
      document.getElementById("storedName").innerHTML = name;
    }
    
    function myFunction() {
      // Gets input value
      var name = document.getElementById("myInput").value;
    
      // Saves data to retrieve later
      localStorage.setItem("userName", name);
      
      // Updates HTML
      updateHTML();
    }

    Note that your code was ok; the only problem was that 2 lines were outside the function, that's all. Then, in your other page, you can use the updateHTML function:

    updateHTML();

    EDIT: I've made an additional function so you can reuse the code when you just have only to retrieve the data. Also, it is always a good idea to separate the code so it is easier to understand and maintain. Hope it helped; let me know if not.