0

I would like the var value to have the same value after refreshing, e.g if the button is pressed 5 times, then the user refreshes, the paragraph 'print' will show 6 instead of 1, which it is set to do currently.

Here is my code:

var value = 1;
$(document).ready(function() {
    $('#print').text(value);
});

$('#add1Button').click(function() {
    value = value + 1;
    $('#print').text(value);
});
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
igetstuckalot
  • 237
  • 2
  • 8
  • 16
  • 1
    make ajax request to some other html and get back the data on document ready. You can also do this using cookies. – Sumit Sahay Feb 19 '16 at 22:08
  • Possible duplicate of [How to get JS variable to retain value after page refresh?](http://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh) – traktor Feb 19 '16 at 23:06

1 Answers1

4

If I understand you correctly, you need to have same value even after user refreshes the page? If that is correct, then you can:

  1. Write that value to cookie
  2. Use local storage
  3. Store the value on server and retrieve it when page is loaded.
  4. (Suggested by PHPglue, thanks): you can use Hash or get value in the url

First option is simplest and supported by all browsers. Local storage is HTML5 feature and you should check which browsers support it. Third option is most complex.

Community
  • 1
  • 1
vmg
  • 9,920
  • 13
  • 61
  • 90