Elmehdi93
Elmehdi93

Reputation: 70

Keep the last selected option in a select after refreshing JQuery

I have a list of cars and a select list that contains car brands and "all", when choosing an option I filter cars based on their brands. e.g when I choose "Mercedes" only Mercedes' cars are displayed, and we I choose all, all the cars are displayed. (It all works just fine).

When I refresh the page I want the list to be filtered based on the last option I chose (before refreshing) and not all the list again. I'm wondering if there's a way to do this on the client side without in need of server side work. I just need to mention that my question is not about the "onchange" function but about storing the last chosen option.

Upvotes: 0

Views: 1069

Answers (1)

lpd
lpd

Reputation: 2337

If you only need it to persist across page refreshes, not different browser sessions, then use the sessionStorage api:

// When changing the filter
var filter = 'Mercedes';
sessionStorage.setItem('last-filter', filter);

// When loading the page (document.ready)
var filter = sessionStorage.getItem('last-filter') || 'all';
if (filter !== 'all') {
    changeFilter(filter);  // your function
}

Only strings can be stored directly. Instead of storing an element, store its element id/class instead. To store other objects, use the JSON.stringify function on your data to serialise it to a string.

If you ever decide you would like the filter to persist across eg browser crashes, then it's easy to switch in the fully compatible localStorage api. Items in localstorage have no specific expiration date, so if expiry is desirable then you'd need to also save the filter date to detect and remove stale items yourself.

Upvotes: 2

Related Questions