Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep a JavaScript variables value after a page refresh? [closed]

i am working with one project in which variable is assigned a value i need that value when browser is refreshed.Is there any way get that value?

like image 591
Anudeep GI Avatar asked Aug 07 '12 08:08

Anudeep GI


People also ask

How do I keep my data after refreshing page in JavaScript?

To store the form data in JavaScript localStorage, we'll use the setItem() method. It stores the data in the localStorage object and takes the key and value parameters as input. The parameters can be later used to retrieve the data when the browser reloads the page or a new session is initiated.

How do you retain value after refreshing?

Answers. Use window. localStorage or window. sessionStorage,sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts.

Which is the correct way of storing a number in a variable in JavaScript?

Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable. For instance, you might create a variable named money and assign the value 2000.50 to it later.


1 Answers

Cookies

The best solution is to use cookies. A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a small piece of data sent from a website and stored in a user's web browser while a user is browsing a website (from Wikipedia).

Using a cookie you can save the state and later read it and use it.

With jQuery it is very easy to use cookies.

To set:

$.cookie("var", "10");

To get:

$.cookie("var")

To delete:

$.cookie("var", null);

Local Storage

When you want to save localy great amount of data, you have another opportunity — to use local storage (since HTML5). You can do it directly using JavaScript or using one of available jQuery plugins.

for example, with totalStorage:

var scores = new Array();
scores.push({'name':'A', points:10});
scores.push({'name':'B', points:20});
scores.push({'name':'C', points:0});
$.totalStorage('scores', scores);
like image 184
Igor Chubin Avatar answered Oct 19 '22 17:10

Igor Chubin