pcs
pcs

Reputation: 1854

Javascript store session value even after click back button

I need to know how I can show the input data of a form after a user presses the back button.

Here is the working jsfiddle

I created a simple asp page.

If I click next after entering some input value, it will go to next page, and again I click back, it doesn't show entered input values.

$("#form").submit(function() {
    var inputs=$('.input');
    for(i=0;i<inputs.length;i++)validateEmail(inputs[i]);
    if($('.invalid').length!==0)return false;
});

I need to show those values. How can I achieve this? Thanks in advance!

Note: In my jsfiddle didn't include next page action.

Upvotes: 0

Views: 2417

Answers (1)

Marco Bonelli
Marco Bonelli

Reputation: 69367

You have several methods, althought I'm not a big fan of cookies because they are not so smart to manage.

You can either use:

  • The localStorage API, if you want your values being saved until the user clears the cache, like this:

    var myValues = [];
    for(i=0;i<inputs.length;i++) {
        validateEmail(inputs[i]);
        myValues.push(inputs[i].value);
    }
    
    // Save them fot later use
    localStorage.myValues = JSON.stringify(myValues);
    
    // After clicking the button you can retrieve them back
    var oldValues = JSON.parse(localStorage.myValues);
    
  • The sessionStorage API, which lives for the current session of the browser (i.e. when the user closes the browser it gets deleted):

    var myValues = [];
    for(i=0;i<inputs.length;i++) {
        validateEmail(inputs[i]);
        myValues.push(inputs[i].value);
    }
    
    // Save them fot later use
    sessionStorage.myValues = JSON.stringify(myValues);
    
    // After clicking the button you can retrieve them back
    var oldValues = JSON.parse(sessionStorage.myValues);
    

NOTE: I'm using JSON.parse and JSON.stringify because both storage objects (local and session) can only store data in string format.

Upvotes: 1

Related Questions