0

I have a counter for button clicks, but if I refresh the page it sets back to '0'. How can I storage the input value so if I close the browser the previous number will remain still?

$(function() {
  $('.counter').click(function() {
    $(this).val(parseInt($(this).val()) + 1);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" class="counter" value="0">
  • 5
    You could use [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) – Rory McCrossan Nov 16 '18 at 10:08
  • you can use AJAX to store new value to database every time a button is pressed so that you can retrieve it any time you want. – Vhndaree Nov 16 '18 at 10:16

3 Answers3

1

We can use any one of these local storage, session storage, cookies, querystring,

Tauqeer
  • 19
  • 1
1

You could use local storage to store a key/value pair. Here is an example of how you could use it:

$(document).ready(function() {  

  //Firstly check if buttonClickCounter is in local storage from before.
  if(localStorage.getItem("buttonClickCounter") === null){
    //buttonClickCounter is not in local storage.

  }else{
    //buttonClickCounter is in local storage.
    var counter = localStorage.getItem("buttonClickCounter");   
    //insert the counter value into the HTML.   
    $('.counter').val(counter);     
  }


  $('.counter').click(function() {
    var newValue = parseInt($(this).val()) + 1;
    $(this).val(newValue);
    //store the new counter value in local storage.
    localStorage.setItem('buttonClickCounter', newValue);   
  });

});

You can check local storage values in the console under the Application tab as follows: enter image description here

Sarah
  • 1,943
  • 2
  • 24
  • 39
0

You can use localstorage or cookies for this.
Take a look at these websites:
Localstorage: Localstorage
Cookies: Cookies

Example localstorage:

var buttonvalue = $('.counter').val();
localStorage.setItem("buttonvalue", buttonvalue);
// get value of button
var someVarName = localStorage.getItem("buttonvalue");

For cookies in Jquery you should include a library:
https://github.com/carhartl/jquery-cookie

Then you can use this:

$.cookie("buttonvalue", $('.counter').val());
var cookieValue = $.cookie("buttonvalue");
Webdeveloper_Jelle
  • 2,868
  • 4
  • 29
  • 55