7

I have created a JavaScript object.

var myObj = {};

Now as user plays-around with the application, we assign some values to this object.

myObj['Name'] = 'Mr. Gates';
myObj['Age'] = 58;

...
...
...
myObj['Role'] = 'CEO';

But whenever the page refresh's, the object looses its values.

Is there any way using HTML 5\or any other technique to persist these values across page refresh.

SharpCoder
  • 18,279
  • 43
  • 153
  • 249
  • that's all about cookie!!! – Bhojendra Rauniyar Apr 17 '14 at 07:51
  • 1
    Side note: Another way to write `obj['Name']` is `obj.Name`. As long as the property name fits the requirements of a JavaScript identifier name (can't have spaces or some other characters, must start with a letter, etc.) you can use the dot notation. For property names that have spaces, etc., or start with something other than a letter, then you need to use bracketed notation. – T.J. Crowder Apr 17 '14 at 07:58

1 Answers1

13

Yes, you have two primary choices:

  1. Using a cookie. Cookies are easy to set from JavaScript, but a bit of a pain to read. You've said you're using jQuery; there's are a couple of jQuery plug-ins that make cookies a lot easier, if you search for "jquery cookie plugin" you'll find them.

  2. Using web storage, which is supported by all major browsers, even IE8. You have two choices: "Session" storage that only lasts for this "session," and "local" storage which persists until the user clears it out or the browser decides it needs that room for something else.

That second option is quite easy to use, you can store things using JSON-formatted strings (the JSON object is also supported by all major browsers):

Storing your object:

localStorage.yourObject = JSON.stringify(obj);

Retrieving your object (for instance, on page load), or a blank object if there's none stored:

obj = JSON.parse(localStorage.yourObject || "{}");

In the above, localStorage is a variabl (and underlying implementation) provided by the browser for local storage. You could use sessionStorage instead if you wanted session storage.

Here's a complete local storage example: Live Copy

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Local Storage</title>
</head>
<body>
  <label><code>Name</code> property for our object:
    <input type="text" id="txtName">
  </label>
  <script>
    (function() {
      var txtName = $("#txtName");
      var obj = JSON.parse(localStorage.yourObject || '{"Name": ""}');
      txtName.val(obj.Name);
      // This is obviously hyperactive:
      txtName.on("change keypress keyup blur paste click", function() {
        obj.Name = txtName.val();
        localStorage.yourObject = JSON.stringify(obj);
      });
    })();
  </script>
</body>
</html>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875