Populate HTML form with data saved on Local Storage

风流意气都作罢 提交于 2019-12-19 11:16:54

问题


My application saves the filled form data (input fields with their ID's and values) to Local Storage and even loads them back successfully, separating the parsed ID's and values back up again.

The problem is that I can't manage to pre-fill the form back up from the data that has been saved to Local Storage once the page reloads. Saved data remains in browser's resources, and console logs the correct values for each input field. However, nothing shows up on the page itself.

Here is an example of my HTML structure:

<form id="myForm" method="post">
   <input type="submit" onclick="dataSave();" value="Save">
   <input class="formField" type="checkbox">Task done!
   <input class="formField" type="text">How it went?
</form>

And here is the current JavaScript that does the saving and loading to Local Storage:

if (typeof(Storage) !== "undefined"){
    
    // Loading data
    function dataLoad(){
        var inputParse = JSON.parse(localStorage.getItem('fieldString'));
        var inputId;
        var inputValue;
        var inputType;

        $.each(inputParse, function(key, value){
            inputId = key;
            inputValue = value;

            if (inputValue === "true" || inputValue === "false"){
                inputType = inputValue;
            }
        });

      
        $(".formField").each(function(){
            inputId = this.id;
            document.getElementById(inputId);
 
            if (inputType === "true"){
                $(inputId).attr("checked", "checked");
            } else {
                $(inputId).val(inputValue);
            }
        });
    }
    
    // Saving data
    function dataSave(){
        var mngrFields = {};
        
        $(".mngr-field").each(function(){
            if (this.type == "radio" || this.type == "checkbox"){
                mngrFields[this.id] = this.checked;
            } else {
                mngrFields[this.id] = this.value;
            }
        });
        localStorage.setItem('fieldString', JSON.stringify(mngrFields));
    }

And to run the dataLoad() after the page has loaded, I have a simple dataLoad(); inside my $(document).ready(function(){ });.

How can I get the form filled up with the saved data? I have tried some document.GetElementById workarounds, but no luck.


回答1:


The task is simple:

  • get localStorage content (but first check is it there);
  • for each stored ID check the HTML type from the DOM (because you don't know it from current localStorage object);
  • assign value or checked attribute (if is radio/checkbox) to it;

So here it is:

function dataLoad() {
    if (localStorage.getItem('fieldString') !== null) {
        var inputParse = JSON.parse(localStorage.getItem('fieldString'));
        $.each(inputParse, function (key, value) {
            var field = document.getElementById(key);
            if(field.type == 'radio' || field.type == 'checkbox'){
                field.checked = value;
            }else{
                field.value = value;
            }
        });
    }
}

You can call the function automatically on document load or assign it to some button (like save action) - it's up to you.

Good luck!



来源:https://stackoverflow.com/questions/38473924/populate-html-form-with-data-saved-on-local-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!