abrunet
abrunet

Reputation: 1122

update cache before unload javascript with form

I have a form which is updated by the user through javascript. Indeed, the user can add some fields dynamically. So far, all is working great. Let's say my form has one field. The user add one more time that field. He validates it, he reached a new page with the results of his form but then realizes he did something wrong and go back (e.g. browser previous button).

The form is still displayed with the previous input but only with one field. (the one he added with javascript does not appear anymore) Can I update somehow the cache after the submit of the form so that if the user go back, he can see the same form that he just submitted?

Cheers!

Upvotes: 0

Views: 85

Answers (1)

PitaJ
PitaJ

Reputation: 15074

Whenever your code changes the form, you should call a function that stores the current form code in the localStorage. Whenever the page is opened, you should check to see if the localStorage contains that information and, if so, set your form code to the stored code. This doesn't update the browser's cache, but it does store the information on the client side.

$(document).ready(function(){

    $("#something").click(function(e){
        e.preventDefault(); 
        // do stuff: add form elements, bla bla bla;
        updateStorage();
    });
    $("#clearStorage").click(function(e){
        e.preventDefault();
        localStorage.removeItem("theUsersPage");
    });

    function updateStorage(){
        var current;
        current = $("#container").html();

        localStorage.setItem("theUsersPage", current);
    }

    function loadFromStorage(){
        var old = localStorage.theUsersPage;
        if(old){
            $("#container").html(old);
        }
    }

    loadFromStorage();

});

jsfiddle: http://jsfiddle.net/JjxV8/1/

Upvotes: 1

Related Questions