Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Local Storage item loading in as string when I need it to be an integer

I’m currently trying to allow users to input a value that is then added to a total and then locally stored. I want to allow the user to load their previous total, and then add more to it through the same input.

What’s actually happening is that when the user loads onto the page, the previously stored value is loaded in as a string. I’m unsure as to how to change this to an integer so as the user can then add another integer to it. This updated total then needs to be displayed to a html element.

//Load current total or set to 0
var calories = localStorage.getItem("calorieCount") || 0;
//Display current total
$('[id=calorieCount]').html(calories);

//On add
$('#calorie-add').click(function () {
      //Take current total and add user input
      calories += parseInt(document.getElementById('adjust-input').value);
      //Update current total to local storage
      localStorage.setItem('calorieCount', calories);
      //Display new total
      $('[id=calorieCount]').html(calories);
    });

I understand that anything that is locally stored is stored as a string, but I’ve seen people mentioning parsing it into an integer and allowing users to manipulate the number. But I’m unsure as to how they’ve achieved this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help is greatly appreciated 😀

>Solution :

You need to parse the local storage value as an int the first time you load it like this:

var calories = parseInt(localStorage.getItem("calorieCount")) || 0;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading