ermac
ermac

Reputation: 438

Remain class from previous page

Simple question here, I've got a button with JavaScript that changes from ON to OFF changing it's class attribute.

So, the default value is OFF, and when you click it, swaps to ON. The problem is that everytime you navigate through the website's pages it always displays as OFF from default even if you selected ON previously.

Is it anyway with JavaScript or jQuery to remain the option selected from the previous page? I'm using class attribute to change the element from ON to OFF

Thanks in advance for your help!

Upvotes: 0

Views: 157

Answers (1)

Hrvoje Golcic
Hrvoje Golcic

Reputation: 3686

There are two ways that comes to my mind where you can get the value from the previous page. In each case the previous page would need to store the data (option value) somewhere and the next page would need to load this data from there.

  1. SERVER-SIDE Solution (Permanent Solution)

    • When user selects the option on the previous page, the page should then send the data to the server via AJAX, or using the <form> element. Server can then store the option into the database, file or session storage...
    • When you load the next page from the server, this page can be set to already include the data on loading or fetch it dynamically via AJAX.
  2. CLIENT-SIDE Solution (Data persistency not guaranteed)

    • When user selects the option on the previous page, the page should then save the data to the local storage of the browser. This means if user clears the data in the browser, it will be lost forever.
    • When you load the next page from the server, just fetch the option from the local storage. It's easy... http://www.w3schools.com/html/html5_webstorage.asp

Furthermore:

  • The data can be stored in cookies. Similar to local storage but will be sent to server with each HTTP request. This would be overhead if you don't need this data on the server. Use local storage instead.

  • The data can be passed in the URL. Only if you want the user to be able to change this data.

Upvotes: 1

Related Questions