jquerylocal-storagedecrement

decrement value localstorage


why is localstorage not doing anything after typing in a value to take out from the current value?

jquery:

$(document).ready(function(){
   var decVal = $(".decVal");
   var currentVal = $(".currentVal");

   currentVal.html(localStorage.getItem("dec"));
   
   $(".decValButton").click(function(){
      var newval = currentVal.val();
      newval = currentVal.val() - decVal.val();
      currentVal.val(newval);
      localStorage.setItem("dec", currentVal.html());
      $(decVal).val("");
   });
});

html:

<div class="container">
  <div class="currentValBox">
    <input class="currentVal" type="text" value="100" readonly>
  </div>
        
  <div class="decBox">
    <button class="decValButton">-</button>
    <input class="decVal" type="text">
  </div>
</div>

let's say you take out 10 from .currentVal by typing 10 in .decVal. the .currentVal value should be 90 now but instead it goes back to the default value 100 after refreshing when it should've stayed 90


Solution

  • instead of using html() use val() to set the value, the problem is you have 100 as default value look here <input class="currentVal" type="text" value="100" readonly> and when you load the page you are not overriding the default value correctly, this is how you do it:

     $(document).ready(function(){
        var decVal = $(".decVal");
        var currentVal = $(".currentVal");
        /* check if there is a value in localStorage if not use 100 as default */
        localStorage.getItem("dec") ? currentVal.val(localStorage.getItem("dec")) : currentVal.val(100);
    
        $(".decValButton").click(function(){
           var newval = currentVal.val();
           newval = currentVal.val() - decVal.val();
    
           currentVal.val(newval);
           localStorage.setItem("dec", newval);
           $(decVal).val("");
        });
     });
    

    another problem is in this line localStorage.setItem("dec", currentVal.html()); you are setting your localstorage variable as an empty string to set it correctly use your newval instead,

    html() means the html content, for example if you have a <div>Hello</div> the html() method will give you Hello as result, for input elements its returns nothing which the case in your example