-2

I want to know how to work with a variable through multiple pages using JavaScript and to keep the modified value, at least until the page is closed.

I got 2 pages sharing the same JavaScript file. I want to modify a variable in one of the pages and to have the modified value when I go to the other page so that way I can work with the new value. I read about "localStorage" but I don't know how to apply it.

  • One of the option is using `querystring` in `url` ... Possible duplicate : http://stackoverflow.com/q/2405355/3279496 ... and solution : http://stackoverflow.com/a/2405630/3279496 – nelek Jan 05 '17 at 06:51

1 Answers1

0

I build a simple jsfiddle to show the basic functionality for localStorage at https://jsfiddle.net/KoizumiGaho/nL0o45y8/7/ You can enter a text in the inputfield and store it. If you run the jsfiddle again, you can load the text from local storage.

Here is the HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="result" placeholder="Enter something..." />
<button id="save">Save</button>
<button id="load">Load</button>

And here is the Javascript

function supports_html5_storage() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch (e) {
    return false;
  }
}

if (supports_html5_storage()) {
  $('#save').click(function() {
    localStorage.setItem("lastname", $("#result").val());
  });
  $('#load').click(function() {
    $("#result").val(localStorage.getItem("lastname"));
  });
} else {
  // Sorry! No Web Storage support..
  alert('No support for local storage!');
}
cringe
  • 13,401
  • 15
  • 69
  • 102