Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript How to code Locale Storage in JS

jmory

Coder
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. All help is appreciated and thank you in advance.

This is my code so far, 1st set is the HTML and then 2nd set is the JS and 3rd set is CSS:
HTML:
<!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/[email protected]/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-->   

<!--CYNTHS 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>

JavaScript:
// 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

CSS:
/* 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%;
}
 
JavaScript:
// START OF CYNTHS JS BUDGET CODE
const stored = localStorage.cynthsBudget?.split('|') || '';

if(stored){
    $('form [id]').each( function(index){$(this).val( stored[index] )} );
    /* adding reset button */
    $('button').after('&nbsp;&nbsp;<button class="btn btn-primary btn-lg btn-block bg-success" title="Reset previously saved data">Reset</button>');
    $('button').eq(1).click(function(){
        delete localStorage.cynthsBudget;
        location.reload();
    });
}

function gather() {
  const budget = $('#budget').val().replace(/\D/g,''),
        necessities = $('#necessities').val().replace(/\D/g,''),
        activities = $('#activities').val().replace(/\D/g,''),
        food = $('#food').val().replace(/\D/g,''),
        transportation = $('#transportation').val().replace(/\D/g,''),
        result = budget - necessities - activities - food - transportation,
        savings = budget * 0.20,
        msg = result == 0
                 ? '<p class="text-danger"> You did not enter anything.</p>'
                    : result < 0
                       ? `<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>`
                          : `<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>`;
  $(".results-data").html(msg);
  if(result > 0) localStorage.cynthsBudget = [budget, necessities, activities, food, transportation].join('|');
}

function centerme() {
const boiheight = $(".center-budget-form").height(),
      middle = boiheight / 2;
$(".center-budget-form").css("margin-top","-" + middle + "px");
//console.log(boiheight);
}

$("button").eq(0).click(gather);
$(document).ready(centerme);
$(window).resize(centerme);
// END OF CYNTHS JS BUDGET CODE
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom