skip to Main Content

I created a code with a local storage and so far so good every other thing saves when the page reloads but the text inside the input field vanishes. What should I do please?

I tried adding the local store data to an input field and created and I was expecting it to save the text when the page reloads but it just didn’t save it.
The input is inside a span element but was created with JavaScript

2

Answers


  1. If the text inside your input field is not persisting after a page reload even though you are using local storage, there are a few things you need to check and modify in your code.
    At the time when the input field value changes, save it to local storage. You can use the input or change event to trigger the save operation.

    // Assuming your input element has an id "myInput"
    const inputElement = document.getElementById('myInput');
    
    inputElement.addEventListener('input', function() {
        const inputValue = inputElement.value;
        localStorage.setItem('inputValue', inputValue);
    });
    

    And the time the page loads, retrieve the input field value from local storage and set it as the initial value.

    window.addEventListener('load', function() {
        const storedValue = localStorage.getItem('inputValue');
        if (storedValue) {
            inputElement.value = storedValue;
        }
    });
    

    Hope this help you 🙂

    Login or Signup to reply.
  2. This example fully works:

    <html>
        <head>
            <script>
            function change() {
                localStorage.setItem("myinput", this.value);
            }
    
            window.addEventListener("load", function() {
                let storedValue = localStorage.getItem("myinput");
                if (storedValue) {
                    document.getElementById("foo").value = storedValue;
                }
            });
            </script>
        </head>
        <body>
            <input type="text" oninput="change" id="foo">
        </body>
    </html>
    

    As you can see, we can make it work. So something went wrong in the way you tried to make it work. Since the input was added via Javascript at your end, there are chances that you attempted to add the event handlers before your input was created. Here I used the oninput attribute on the input which will have the event handler even if the input was added via Javascript.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search