Question

I have a form with some show/hide sections. When I press some buttons in my home form, different forms will be shown. After I edit the information in those forms I'm returning to the first form. But the state of the show/hide sections is reseted. The show/hide action is done with jquery toggle. The state of these sections needs to be kept on returning. So I'm thinking of storing the state of each section in session variables. Do you have other solutions? Would it be better or possible to have this behavior in a separate place, for example in a middleware?

Was it helpful?

Solution

You don't really need session storage. In the case you've described, you want the sections' show/hide status to be kept between pages, for a single client. Session would be overkill, as it involves the server for something trivial.

My go would be to use something like localStorage (or cookies if you really want) directly in the jQuery. It will stay on the client and the server will not mind.

EDIT

Function to check for localStorage:

var canHazStorage = function () {
    "use strict";
    try {
        return 'localStorage' in window && window.localStorage !== null;
    } catch(e) {
        return false;
    }
};

You would need to change the toggling code to set a value:

$('#section1').toggle();

if ( canHazStorage ) {
    if ( is_shown ) { // you'll need to write that yourself
        window.localStorage['section1'] = true;
    } else {
        window.localStorage['section1'] = false;
    }
} else {
    // same code using cookies
}

And in init function:

if ( canHazStorage ) {
    var toggled = window.localStorage['section1'];
    $('#section1').toggle(toggled);
} else {
    // same code using cookies
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top