简体   繁体   中英

Save form data in browser session

I have an div that is shown when a form is submitted, but when I refresh the page, my data disappears and I'm searching for a way to preserve my data on page refresh.

I know how to save data in a session, but not an entire form. How do I approach this issue? Is it even possible to save an entire form with Javascript?

 function showHide() { var div = document.getElementById("hidden_form"); if (div.style.display == 'none') { div.style.display = ''; } else { div.style.display = 'none'; } }
 <form name="product_form" id="product_form" enctype="multipart/form-data" action="admin_products.php" method="post" accept-charset="utf-8" onsubmit="showHide(); return false;"> <input type="textfield" id="title" name="title" value="" readonly> <div id='hidden_form' style="display:none"> <input type="text" id="name" name="name" value="" placeholder="Product Name"> <label id="option_1" name="option_1">Option Name</label> <input type="text" id="optionn" name="optionn" value="" placeholder="Product Name"> </div> <input type="submit" id="add" name="add" value="Save" class="" <!--onclick="myFunction()-->">

When you hit submit , you'll reload the page and lose your data. By using localStorage and JSON.stringify() you are able to save the data locally in your browser and fetch it when you load your page.

Since localStorage can only store strings, you'll have to convert your object to a string. That's where JSON.stringify() comes into play. And when you fetch it, you can use JSON.parse() to convert it back to an object.

 $("#btnSubmit").click(function() { var data = {}; data.Text = $("#myText").val(); data.isProcessed = false; localStorage.setItem("myData", JSON.stringify(data)); }); //On load var data = localStorage.getItem("myData"); var dataObject; if (data != null) //There's stored data { dataObject = JSON.parse(data); $("#myText").val(dataObject.Text) localStorage.removeItem("myData"); //Remove data, otherwise it'll be there for a long time. }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <form method="post"> <input type="text" id="myText" /> <button type="submit" id="btnSubmit">Submit</button> </form> </div>

More information on localStorage: W3Schools
More information on JSON.stringify and JSON.parse: MDN

I don't know if the snippet will work, since it'll submit a post. Copy this snippet and try it on your local system.

EDIT As I made a tiny mistake myself, I updated my snippet. But as I suspected, SO doesn't allow access to localStorage.

And ofcourse, you'll have to put this code in your $(document.ready(function() { ... }); for it to work. I did forget to add a <form></form> to my HTML snippet. And I just tested it on my local system and it's working fine.

You can try with localStorage . It's key-value storage that all modern browsers have. There're simple libraries to write to localStorage with fallback to cookies if you need old browser support (written by javascript instead of server side scripts).

I'll give you an example with localStorage :

    //emulating that the form was showed (save clicked) and the value true stored on the localStorage
    localStorage.setItem('displayedForm', true);

    //initializing the state of the page
    initialize();

    function showHide() {
        var div = document.getElementById("hidden_form");
        if (div.style.display == 'none') {
            div.style.display = '';
            localStorage.setItem('displayedForm', true);//if the conditions are meet to display the form, store it on the localStorage
        } else {
            div.style.display = 'none';
            localStorage.setItem('displayedForm', false);//if the conditions are **NOT** meet to display the form, store it on the localStorage as well
        }
    }
    function initialize() {
        if (localStorage.getItem('displayedForm') === true || localStorage.getItem('displayedForm') === 'true') {
            var div = document.getElementById("hidden_form");
            div.style.display = '';
        }
    }

Working Fiddle: https://jsfiddle.net/y0uep73e/

Facing this problem myself, I wrote a simple library to automatically handle saving and loading form data via local storage: https://github.com/FThompson/FormPersistence.js

Example which saves data upon unload and loads data upon load:

<script src='https://cdn.jsdelivr.net/gh/FThompson/FormPersistence.js@1.0.1/form-persistence.min.js' type='text/javascript'></script>
<script type='text/javascript'>
    window.addEventListener('load', () => {
        let myForm = document.getElementById('my-form')
        FormPersistence.persist(myForm)
    })
</script>

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