How to Code Local Storage in JS?

Hi, I was hoping if someone can help me with Local Storage using JavaScript. I am trying to create an budget application and would like all the values that are inputted into the fields to be saved in the local storage but I can 't seem to figure it out.

This is my code so far, 1st set is the HTML and then 2nd set is the JS and 3rd set is CSS:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--BOOTSTRAP LINKS FOR BUDGET-->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/open-iconic/1.1.1/font/css/open-iconic-bootstrap.min.css"/>
    <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Unica+One&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./assets/css/style.css">
    <title>Stormy Budget Exchange</title>
</head>

<!--START OF CYNTHS BUDGET SECTION-->
<section id="cynthia">
  <div class="container-fluid center-budget-form">
    <div class="row">
      <div class="col-sm-6 col-sm-offset-1">
        <div class="box-it">
                <form>
    <input class="form-control input-lg" type="text" id="budget" placeholder="Budget"/>
    <input class="form-control input-lg" type="text" id="necessities" placeholder="Necessities"/>
    <input class="form-control input-lg" type="text" id="food" placeholder="Food"/>
    <input class="form-control input-lg" type="text" id="activities" placeholder="Activities"/>
    <input class="form-control input-lg" type="text" id="transportation" placeholder="Transportation"/>
        </form>
        <button class="btn btn-primary btn-lg btn-block bg-danger">Get Budget</button>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="results">
          <h1 class="title">Results</h1>
          <div class="results-data">
            <p>Use the form to enter your total budget and expenses and hit the Get Budget Button!</p>
          </div>
        </div>
      </div>
</section>
 
 <!--END OF CYNTHS BUDGET SECTION-->   

<!--CYNTHIA'S JQUERY CDN AND MIN JS FOR BUDGET--> 
      <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
    <script src="./assets/js/budget.js"></script> 


  
</body>
</html>
// START OF CYNTHS JS BUDGET CODE

$("button").click(gather)
$(document).ready(centerme);
$(window).resize(centerme);

function gather() {
  budget = document.getElementById("budget").value;
  budget = budget.replace(/\D/g,'');
  necessities = document.getElementById("necessities").value;
  necessities = necessities.replace(/\D/g,'');
  activities = document.getElementById("activities").value;
  activities = activities.replace(/\D/g,'');
  food = document.getElementById("food").value;
  food = food.replace(/\D/g,'');
  transportation = document.getElementById("transportation").value;
  transportation = transportation.replace(/\D/g,'');
  result = budget - necessities - activities - food - transportation;
  savings = (budget * 0.20);
  $(".results-data").empty();
  if (result === 0) {
    $(".results-data").append('<p class="text-danger"> You did not enter anything.</p>');
  }
  else if (result < 0) {
    $(".results-data").append('<p class="text-danger"> After your expenses you have $' + result + ' left in your budget. You might want to try reducing your spend limit during this trip.</p>');
  }
    else {
      $(".results-data").append(
      '<p class="text-sucess"> After your expenses you have $' + result + ' left in your budget.</p>','<p class="text-sucess">But you should save at least $' + savings + '.</p>')
  }
}

function centerme() {
boiheight = $(".center-budget-form").height();
middle = boiheight / 2;
$(".center-budget-form").css("margin-top","-" + middle + "px");
console.log(boiheight);
}
// END OF CYNTHS JS BUDGET CODE
/* BUDGET CSS */
input {
      display: block;
      padding: 5px;
      margin: 12px auto;
      width: 100%;
}
    
.results {
    min-height: 20px;
    padding: 19px;
    margin: 20px 0 ;
    background-color: #f5f5f5;
    border: 1px solid #e3e3e3;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
    
.center-budget-form {
    position:absolute;
    top: 35%;
    width: 50%;
    margin-left: 350px;
    padding: 10px;
    clear: both;
    background-color:skyblue;
    opacity: 95%;
    border-radius: 6%;
}

You can access localStorage (or/and sessionStorage) as an item/value pair, using setItem and getItem.
You can create an object for example:

var budgetObject = { budget: budget, necessities: necessities ...etc}

and store it in localStorage as an item like this:

localStorage.setItem('budget', JSON.stringify(budgetObject));

Now, to retrieve the object from localStorage:

var budgetLocalStorageObject = JSON.parse(localStorage.getItem('budget'));

The data of sessionStorage is only available for the duration of the current browser session. When the user closes their web browser or tab, the data stored in session storage is deleted.

On the other hand, the localStorage data persists even after the user closes their web browser or shuts down their device. This data remains available until it is explicitly cleared by the user or the application.

Avoid to store sensitive data as credit card numbers, api keys etc.

Kostis

HI @domus71 Thank you for assisting, I appreciate it.

I tried using your method but somehow, when I try to enter numbers as the values into the fields in the form. It won’t store in the local storage when I inspect it. Is it because a number will automatically be applied as a string and we wouldn’t need to stringify it? And if so, what would the code look like then?

The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

I always recommend to do a comprehensive reading to the official language reference / docs before coding, it saves time and struggle :smiley:

Best regards!

You can use parseInt(your_number) to convert string to number. If the value is null or not numeric, you will get a NaN. You need to check if your value is a valid number.

Kostis