Search code examples
javascripthtmlwindowlocal-storageonbeforeunload

Save value in reload page javascript


I want to save data in the input when the page reloading and I don't know why my code doesn't work. This is my html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
        <label>nom:</label> <input type="text" value=""/></br>
        <label>prenom:</label><input type="text" value=""/>
        <script type="text/javascript">
        window.onbeforeunload = function(){
        localStorage.setItem(nom, document.getElementsByTagName('input')[0].value);
        localStorage.setItem(prenom, document.getElementsByTagName('input')[1].value);
            }
    document.addEventListener("DOMContentLoaded",function(){
            var nom = localStorage.getItem(nom);
            var prnom = localStorage.getItem(prenom);
            if(nom!==null&&prenom!==null) {                 
            document.getElementsByTagName('input')[0].value = nom;
            document.getElementsByTagName('input')[1].value = prenom;
            }
        });

         </script>
</body>
</html>

Solution

  • Make sure to use quotes for the variable name:

    localStorage.setItem('nom', document.getElementsByTagName('input')[0].value);
    

    Or you can use this which is simpler:

    localStorage.nom = document.getElementsByTagName('input')[0].value;
    

    Your code was setting the localStorage values when the page was loaded which means it set it to be no text so the code won't save.

    Use the below code:

    window.onbeforeunload = function() {
      var nom = localStorage.nom;
      var prnom = localStorage.prenom;
      if (nom !== null && prenom !== null) {
        document.getElementsByTagName('input')[0].value = nom;
        document.getElementsByTagName('input')[1].value = prenom;
      }
    };
    <label>nom:</label> <input type="text" onchange="localStorage.nom = document.getElementsByTagName('input')[0].value" /></br>
    <label>prenom:</label><input type="text" onchange=" localStorage.prenom = document.getElementsByTagName('input')[1].value" />

    IMPORTANT: use the code on your computer because localStorage doesn't work on stack overflow snippets