In PHP we use session variables to store information. You can do the same thing with jQuery. Here is how you can do it using sessionStorage and localStorage. Additionally, this code below is not dependent on jQuery, it will work with javaScript alone. #javascript #jquery

Set the jQuery Session

// Setting a session variable
sessionStorage.setItem('key', 'value');

Now Get the jQuery Variable

// Getting a session variable
var value = sessionStorage.getItem('key');
console.log(value); // Output: 'value'

Remove A Session Variable

// Removing a session variable
sessionStorage.removeItem('key');

Remove All Sessions

// Clearing all session variables
sessionStorage.clear();

About Using Session Storage in jQuery

sessionStorage data is cleared when the page session ends (i.e., when the browser or tab is closed).

If you need persistent storage across sessions, use localStorage instead.

How to Use localStorage

Here is how you would do it using localStorage.

Setting localStorage

// Setting a localStorage variable
localStorage.setItem('key', 'value');

Getting the Value

// Getting a localStorage variable
var value = localStorage.getItem('key');
console.log(value); // Output: 'value'

Removing LocalStorage Variable

// Removing a localStorage variable
localStorage.removeItem('key');

Clearing All localStorage Variables

// Clearing all localStorage variables
localStorage.clear();

How you Can Use in HTML

You can use these stored sessions like this. For example you can use in a form field.

// Populate an input field with a value from localStorage
document.addEventListener('DOMContentLoaded', function () {
    const inputField = document.getElementById('exampleInput');
    const storedValue = localStorage.getItem('key');
    if (storedValue) {
        inputField.value = storedValue;
    }

    // Save the input value to localStorage on change
    inputField.addEventListener('input', function () {
        localStorage.setItem('key', inputField.value);
        document.getElementById('display').textContent = inputField.value;
    });

    // Display the stored value in a div
    if (storedValue) {
        document.getElementById('display').textContent = storedValue;
    }
});

The Form

  <form><label for="exampleInput">Enter something:</label>
  <input type="text" id="exampleInput" placeholder="Type here..."></form>

Use In Other HTML Parts

 // Display the stored value in a div
    
var value = localStorage.getItem('key');
document.getElementById('display').textContent = value;

Use sessionStorage if you want the data to be cleared when the session ends. localStorage data persists even after the browser or tab is closed.In the file download for my subscribers you can see this is action. Just unzip the files after download and examine the code on how it works.



Sign Up To Comment