简体   繁体   中英

Trying to get text input values to stay after refresh with localStorage, what's wrong with my code?

I am trying to get new input values in a given textbox to save even after refreshing. Here is my attempt:

Event handler script:

//store value after changes
function store(){
    var text = document.getElementById("qty").value;
    localStorage.setItem("qty",text);
}
//local storage to keep values after refresh
function getValue(){
    var storedText = localStorage.getItem("qty");

    if(storedText != null){
        document.getElementById("qty").value = storedText; 
    }
    else
        document.getElementById("qty").value = 0;
}

Event registration script:

document.getElementById("qty").onkeyup = store;
document.getElementById("qty").onload = getValue;

HTML:

<input type="text" id="qty" name="qty" class="small w-25 text-right" value="1">

My reasoning is that, once values are changed ( onkeyup ), set the new value into localStorage . Then if I refresh page, onload should activate and use getValue() to set the textbox value to the previously set localStorage value. However, when I refresh, it's always 1. I think I may be misunderstanding something regarding localStorage . Any help is appreciated thanks.

*EDIT: got it to work thanks to comment below by changing getValue to getValue()

However now I have this new problem:

I have the text input box on multiple pages. Now that I've got it to work on saving new input, it also changes the input value of all the other text boxes because they all have the same id. Would there be a way to make them save their own modified values instead of all the same without changing ids?

I tested this on jsfiddle - ( https://jsfiddle.net/dyLbgfk2/17/ ), switched this line:

document.getElementById("qty").onload = getValue;

To:

document.getElementById("qty").onload = getValue();

It appears to work as intended with this slight modification.

Thanks to @Heretic Monkey for pointing out that the input element has no onload event.

It would be better to do this with your code and have this run once the DOM has loaded:

document.addEventListener("DOMContentLoaded", function() {
    //document.getElementById("qty").onkeyup = store;
    //Better to use .addEventListener()
    document.getElementById("qty").addEventListener("keyup", store, false); 
    getValue(); // Just call the function as this event will fire once the DOM
                //Including your input has loaded
});

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