0

I'm trying to make a form where the user input is stored as local storage data. When the user submits, the data gets stored and the browser opens another html file.

What happens is: the data gets stored in the browser's LocalStorage in the first page only, so when I try to retrieve it in the second page nothing happens.

<script>
    function x() {
        let y = document.getElementById("txt").value;
        localStorage.setItem("a",y);
        return false;
    }
</script>
<body>
    <form action="x1.html" >
        <input type="text" id="txt"/>
        <input type="submit" value="click" onclick="x();"/>
    </form>
</body>
<body>
    Ciaoo <span id="z"></span> !!
    <script>
        document.getElementById("z").InnerHTML=localStorage.getItem(a);
    </script>
</body>

I expect the output of page 2 to show LocalStorage content in the mark. There's no error messages.

wazz
  • 4,953
  • 5
  • 20
  • 34
  • 2
    I think you are missing quotes for the getItem? -> InnerHTML=localStorage.getItem('a'); You can always check your localStorage values via the browser inspector, just in case. – Bert Maurau Oct 31 '19 at 23:08
  • Also make sure you type `innerHTML` with a lowercase i – agrm Oct 31 '19 at 23:14
  • `document.getElementById("z").innerHTML = localStorage.getItem("a");` should do the job – Sean Oct 31 '19 at 23:16
  • I checked the browser's local storage and as said it only has the var I try to store in the first page. As soon as it goes to the next web page which is also a local page it disapears from local storage. Already corrected the syntax and it still doesn't work –  Nov 01 '19 at 00:09
  • Does it help if you use `window.localStorage.setItem` etc.? – wazz Nov 01 '19 at 03:29
  • It sounds strange, make sure your code doesn't clear localStorage in other places by using `localStorage.clear()` – ChickenSoups Nov 01 '19 at 03:34
  • If you submit, does the js actually run, or do you go to the next page *first*? https://stackoverflow.com/questions/8082846/form-submit-execute-javascript-best-practice and/or https://stackoverflow.com/questions/8133712/execute-javascript-code-straight-before-page-submit. – wazz Nov 01 '19 at 03:38
  • @wazz I tryed it but it doesn't work.. and yes, the js runs because when I check browser storage in local storage the var is there stored. –  Nov 02 '19 at 14:45
  • No, there is no localStorage.clear() in my code. Now I tryed with sessionStorage instead of localStorage. What happens in this case is: the var I want to store goes to the next page but the sessionStorage.getItem doesn't work. –  Nov 02 '19 at 14:47
  • Ok, it worked with sessionStorage instead of localStorage technique. Still wanna investigate why localStorage didn't work in this case –  Nov 02 '19 at 14:54

0 Answers0