Populate HTML form with data saved on Local Storage

前端 未结 1 1264
闹比i
闹比i 2021-01-16 05:55

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

相关标签:
1条回答
  • 2021-01-16 06:35

    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!

    0 讨论(0)
提交回复
热议问题