What's the best way to incorporate local storage into my Calculator application?

I'm currently working on a calculator project and I have all the necessary resources at hand. The only thing left to do is to incorporate LocalStorage beneath the Result section. This way, the Calculator will keep track of each result until the session is cleared.

For instance:

"1+1=2," 2*2=4, 8/8=1

Localstorage: 2,4,1

function clear()
{
    number1.value = "";
    number2.value = "";
}
function clearresult()
{
    result.innerText = '';
}
function calc()
{
    var number1 = parseFloat(document.getElementById('number1').value);
    var number2 = parseFloat(document.getElementById('number2').value);
    var oper = document.getElementById('operators').value;
    if ( !isNaN(number1) && !isNaN(number2) )
    {
        if ( oper === '+' )
        {
            result.innerText = document.getElementById('result').value = parseFloat(number1) + parseFloat(number2);
        }
        if ( oper === '-' )
        {
            result.innerText = document.getElementById('result').value = parseFloat(number1) - parseFloat(number2);
        }
        if ( oper === '/' && number1 )
        {
            result.innerText = document.getElementById('result').value = parseFloat(number1) / parseFloat(number2);
        }
        if ( oper === '*' )
        {
            result.innerText = document.getElementById('result').value = parseFloat(number1) * parseFloat(number2);
        }
        clear();
        for (var i = 0; i < localStorage.length; i++)
        {
            localStorage.setItem('resultstorage', result.innerText);
            output.innerText = localStorage.getItem('resultstorage');
        }
    }
    else
    {
        alert("No numbers were entered!");
        clear();
        clearresult();
    }
}

Answer №1

*save your outcome in an array and then store that array in local storage according to the instructions provided below

let list = []
localStorage.setItem('items', JSON.stringify(list))
const data = JSON.parse(localStorage.getItem('items'))

adding new result to the array

list.push(input.value)
localStorage.setItem('items', JSON.stringify(list))  

delete the array from local storage

localStorage.clear()

Answer №2

If you're looking for a helpful solution, consider the following approach: - You can eliminate verbose code by removing default variables as needed.

// Function to save the result and update the DOM accordingly
const saveResult = function (result, storageName = 'resultstorage') {
  let store = []
  store.push(result)
  localStorage.setItem(storageName, JSON.stringify(store))
  // Update DOM with the value
  getResult()
}

// Using try-catch statement ensures error handling when retrieving data from localStorage
const getResult = function (storageName = 'resultstorage') {
  let result;
  try {
    result = JSON.parse(localStorage.getItem(storageName))
    document.querySelector('#output').innerHTML = result
  } catch (err) {}
}

// Use remove instead of clear to avoid unintended removal of other values in storage
const removeResult = (storageName = 'resultstorage') => localStorage.removeItem(storageName)

// Example usage
let value = 23
saveResult(value)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...

Blending a series of filter lists together

I am trying to combine the firstname and lastname as a single filter input. Currently, I have 4 filters that work fine individually. How can I create a single input for both first name and last name so that when a user types a name, it will search for ma ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...

Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeat ...

What is the best way to create a shell script using Node.js?

Currently, I am looking to utilize a shell script with NodeJs on my Windows platform to read a CSV file, perform processing via REST API call, and save the output in another CSV file. ...

What is the best way to receive a user's input date in Dynamics 365 using HTML/JavaScript?

My HTML webform is set up to capture user input like address, card number, city, and state in text format. However, within Microsoft Dynamics 365, I have a custom entity with fields for this information. When a user completes the webform and submits it, a ...

Update Button Colour upon clicking the Button

I have multiple buttons lined up in a row on my webpage. I want the button's color to change when I click on them. Below is a snippet of my code: $( "button.change" ).click(function() { $(this).toggleClass( "selected" ); }); .Button { font-fa ...

What could be causing Axios to send requests prior to the component mounting?

My application consists of a React frontend and a Spring backend. I am using Axios to fetch data from the backend. There are two class components containing tables, which can be accessed through a menu component (only in componentDidMount and componentDidU ...

Modify button behavior on click after the initial press

Struggling to make this work the way I want. I have a button that should execute Javascript function A when clicked, and in function A, I need to change the onclick attribute to function B. This way, on the second tap of the button, it will trigger functio ...

Changing z-coordinate from perspective to orthographic camera in three.js

In my project, I am trying to blend perspective objects (which appear smaller as they move farther away) with orthographic objects (which maintain the same size regardless of distance). The perspective objects are a part of the rendered "world," while the ...

What is the method to show text on hover in angularjs?

I'm a beginner in AngularJS and I'm looking to show {{Project.inrtcvalue}} when the mouse hovers over values. Can anyone guide me on how to achieve this using AngularJS? <table ng-table="tableParams" show-filter="true" class="table" > ...

PHP not displaying Bootstrap input validation message set by JS

Currently, I am attempting to implement error messages using .setCustomValidity() and the .invalid-feedback class on an HTML form utilizing Bootstrap 4. Essentially, when the user validates the form, a JavaScript script assesses the inputs and if any erro ...

A different approach for dynamically displaying React components sourced from an API

As I develop a website using Next.js/React that pulls in content from Strapi CMS, my goal is to create a dynamic page template for news articles. The aim is to empower content editors by giving them the flexibility to choose the type of content they wish t ...

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

Is it possible to preserve and recover the navigation history in react-navigation within react-native?

In my app, I have a main StackNavigator(1) that consists of 5 different screens. However, after reaching the 3rd screen, I need to navigate to another StackNavigator(2) screen. Once certain actions are completed on the second StackNavigator(2) screen, the ...

A potential memory leak occurs in Nuxt on the client side when dynamically loading a component

I'm currently working on a NuxtJS application where I need to dynamically load components. While my code successfully loads the component on the server-side, the browser seems to encounter a significant memory leak during page loading, making it impos ...

Creating vibrant row displays in Vue.js: A guide to styling each row uniquely

I am not a front-end developer, so Vue and JS are new concepts for me. Currently, I am working on an application for managing sales. One of the components in my project involves displaying invoices in a list format. To make the rows visually appealing, I ...

Guide on incorporating an Ajax spinner to a Slideshow

I am in need of assistance with creating a manual slideshow that includes an ajax loader image. The goal is to display the loader image every time I click on the Previous or Next buttons, until the Test 1, Test 2, and Test 3 texts are fully loaded. Any sug ...

How can I position images in the center evenly?

I am currently working on implementing a 3D image carousel. It seems to work fine with an odd number of images, but when I add an even number of images and the positions change, the alignment gets offset to the left instead of center. Here is the link to ...

Node.js and Express constantly face the challenge of Mongoose connecting and disconnecting abruptly

I have been running an Express (Node.js) app connected to MongoDB using Mongoose for a while now. Everything was working smoothly until recently, when it started acting up. It appears that the server is establishing a connection with MongoDB only to disco ...