Ramez GaIal Ramez GaIal - 3 years ago 207
Javascript Question

How to save results to localStorage

I am new in

HTML
and
jQuery
, and this was my first implementation, and I am not sure it's correct, I need your help, I tried to make simple counter to begin counting per click, and to store the results in
localStorage
, this is all I could do
but it didn't work, may you tell me what I've done wrong?

Thanks






$(function() {
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++
$('.counter[data-page="' + btn + '"]').html(element);

localStorage.setItem('save', $('.counter[data-page="' + btn + '"]').html());

if (localStorage.getItem('save')) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save'));
}
});
});

ul {
padding: 0;
margin: 0;
list-style: none;
}

a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}

ul li {
display: inline-block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li data-page="facebook">
<a href="#" class='counter' data-page="facebook">4100</a>
</li>

<li data-page="twitter">
<a href="#" class='counter' data-page="twitter">4100</a>
</li>
</ul>




Answer Source

You need to init first your buttons with values from localStorage. Then you don't need to retrieve them again, you just need to manipulate the value inside the html and to set the new counter in the localStorage.

Also you need to have one counter by button in your localStorage

// Just to make this snippet work,
// because localStorage is forbiden here

// database = localStorage
database = {
  store: {},
  getItem: function(key) {
    return this.store[key];
  },
  setItem: function(key, val) {
    this.store[key] = val;
  },
}

$(function() {
  $(".counter").each((_, element) => {
    const $btn = $(element);
    const key = `save-${$btn.attr("data-page")}`;
    
    $btn.html(database.getItem(key) || 0);
  });
  
  $(".container li").click(function() {
    const $btn = $(this).find(".counter");
    const key = `save-${$btn.attr("data-page")}`;
    const counter = (+$btn.html()) + 1;

    $btn.html(counter);
    database.setItem(key, counter);
  });
});
ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

a {
  text-decoration: none;
  background: blue;
  color: #fff;
  padding: 10px;
}

ul li {
  display: inline-block;
}
<ul class="container">
  <li data-page="facebook">
    <a href="#" class="counter" data-page="facebook">4100</a>
  </li>

  <li data-page="twitter">
    <a href="#" class="counter" data-page="twitter">4100</a>
  </li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download