简体   繁体   中英

Trying to use localStorage to store user-inputted text in textarea, but Save and Reload buttons are not working

I'm trying to use localStorage to store user-inputted text in textarea - I have a Save button to save the data to localStorage and a Reload button to retrieve the data to localStorage.

However, even though I am receiving screen alerts and the console is telling me that the button is working properly, everytime I enter data into the textarea and click "Save", then delete the data and click "Reload", nothing reloads.

Curiously, it does reload if I refresh the page and click "Reload", but not if I'm on the same page continuously.

I am confused as to why - am I not using localStorage properly? Is there something wrong with my JavaScript functions?

Here is my code:

<html>
<head></head>
<body>
To Do:<p>
<textarea id="todo" cols="50" rows="10">
</textarea><p>
<button id="save">Save</button>
<button id="reload">Reload</button>

<script type="text/javascript">

//save entered info
document.getElementById("save").addEventListener("click", function ()
    {
        var todo = document.getElementById("todo").value ;
        localStorage.setItem("todo", todo) ;
        alert("Saved To-Do List") ;
        console.log("Saved To-Do List")
    } , false);

//reload last session
document.getElementById("reload").addEventListener("click", function ()
    {
        document.getElementById("todo").innerHTML = localStorage.getItem("todo");
        alert("Reloaded To-Do List") ;
        console.log("Reloaded To-Do List")
    } , false);
    
</script>
</body>
</html>

Replace This line document.getElementById("todo").innerHTML ='Your code' to this document.getElementById("todo").value ='Your code' .

Try this code it's works

<html>

<head></head>

<body>
  To Do:<p>
    <textarea id="todo" cols="50" rows="10">
</textarea>
  <p>
    <button id="save">Save</button>
    <button id="reload">Reload</button>

    <script type="text/javascript">

      //save entered info
      document.getElementById("save").addEventListener("click", function () {
        var todo = document.getElementById("todo").value;
        localStorage.setItem("todo", todo);
        alert("Saved To-Do List");
        console.log("Saved To-Do List")
      }, false);

      //reload last session
      document.getElementById("reload").addEventListener("click", function () {
        document.getElementById("todo").value = localStorage.getItem("todo");
        alert("Reloaded To-Do List");
        console.log("Reloaded To-Do List")
      }, false);

    </script>
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM