Seamless mathematical computations while navigating through Javascript

I have created a basic JavaScript calculator that works efficiently. However, after obtaining the result by pressing the "=" button, I would like the returned result to be saved for future use. The "=" button should be capable of being clicked again to retrieve the same result and then add it to the previously saved result.

I have experimented with various methods, such as doubling the result (which actually multiplies instead of adding), utilizing the eval() function, and appending a "+" string to the end of the result, but none have provided the desired outcome.

TLDR: In any calculator program, when you input "2+2" and press equals, you receive 4. Pressing equals again should yield 6 ("2+2+2").

Below is the code snippet of my current implementation:

var disp = document.getElementById("calc-output"),
  acceptedInputs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "-", ".", "+", "*", "/"];

function ud(n) {
  if (acceptedInputs.includes(n)) {
    if (disp.innerHTML.length == 31) {
      disp.innerHTML = 0;
    }
    if (disp.innerHTML.length < 18) {
      if (disp.innerHTML != 0) {
        disp.innerHTML += n;
      } else if (acceptedInputs.slice(11, -1).includes(n)) {
        disp.innerHTML = 0 + n;
      } else if (disp.innerHTML.toString().slice(1, 2) == ".") {
            if (disp.innerHTML.toString().split(".").length-1 <= 1) {
                disp.innerHTML += n;
            }
      } else {
        disp.innerHTML = n;
      }
    }
  }
}

function answer() {
  if (eval(disp.innerHTML) == disp.innerHTML) {
    disp.innerHTML = disp.innerHTML + "+"
  }
  c = eval(disp.innerHTML);
  disp.innerHTML = c;
}

function clear() {
  disp.innerHTML = "0";
}

function back() {
  var str = disp.innerHTML.toString();
  if (disp.innerHTML != 0 || str.charAt(1) == ".") {
    if (str.length >= 2) {
      str = str.slice(0, -1);
      disp.innerHTML = str;
    } else {
      disp.innerHTML = 0;
    }
  }
}

document.getElementById("n1").addEventListener("click", function() {
  ud(1);
});
document.getElementById("n2").addEventListener("click", function() {
  ud(2);
});
document.getElementById("n3").addEventListener("click", function() {
  ud(3);
});
document.getElementById("n4").addEventListener("click", function() {
  ud(4);
});
document.getElementById("n5").addEventListener("click", function() {
  ud(5);
});
document.getElementById("n6").addEventListener("click", function() {
  ud(6);
});
document.getElementById("n7").addEventListener("click", function() {
  ud(7);
});
document.getElementById("n8").addEventListener("click", function() {
  ud(8);
});
document.getElementById("n9").addEventListener("click", function() {
  ud(9);
});
document.getElementById("zero-button").addEventListener("click", function() {
  ud(0);
});
document.getElementById("comma-button").addEventListener("click", function() {
  ud('.');
});

document.getElementById("plus-button").addEventListener("click", function() {
  ud('+');
});
document.getElementById("minus-button").addEventListener("click", function() {
  ud('-');
});
document.getElementById("multi-button").addEventListener("click", function() {
  ud('*');
});
document.getElementById("div-button").addEventListener("click", function() {
  ud('/');
});
document.getElementById("back-button").addEventListener("click", function() {
  back();
});
document.getElementById("clear-button").addEventListener("click", function() {
  clear();
});
document.getElementById("equals-button").addEventListener("click", function() {
  answer();
});

Answer №1

Store the previous operation (e.g. " + 2") in a variable when the user clicks equals. Then, when the user clicks again, simply add the stored value to the string displayed on screen.

let lastOperation = null;

function processAnswer() {
    if (eval(display.textContent) == display.textContent) {
        // apply the last operation to the displayed number
        display.textContent = display.textContent + (lastOperation ? lastOperation[0] : '');
    }
    // identify the last operation as + | - | * | /
    lastOperation = display.textContent.split(new RegExp('(\\+|\\-|\\*|/).*$'));
    let result = eval(display.textContent);
    display.textContent = result;
}

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

Establishing a connection between a frontend Javascript client and a backend Node.js/express server

Recently, my close friend successfully created a working client website using Javascript. Meanwhile, I have managed to get my server code up and running smoothly, extracting specific data through MySQL. We are now seeking some advice on how we can link t ...

Automatically create CSS properties for left and top using absolute positioning

When looking at these websites as models: On each of them, I noticed that there is a well-organized column of boxes for every post. I attempted to recreate this using various methods, but couldn't achieve the exact layout on my own website. It seems ...

Triggered by each user interaction, the callback function is activated

I need to add a timeout feature to my AngularJS web application. Each time a user interacts with the site, a timer is set for 10 minutes. Once this timer runs out on the client-side, a request is sent to the server signaling a timeout. What is the best wa ...

JSX conditional rendering not behaving unexpectedly

Having difficulty with a conditional JSX statement causing an element to not display properly unless the window is resized. Please note that it works fine in development mode but does not show correctly after building. The goal is to show navigation links ...

What techniques can I utilize to ensure Azure function generates JSON specifically for web browsers?

I have a functioning Azure function with the following code: module.exports = function(context, req) { // this is the complete source code, believe it or not context.done(null, {favoriteNumber: 3}); }; When I utilize a tool like Postman to access ...

There was a failure to establish a Redis connection to the server with the address 127.0.0.1 on port 6379

Currently, I am working with node.js using expressjs. My goal is to store an account in the session. To test this out, I decided to experiment with sessions by following the code provided on expressjs var RedisStore = require('connect-redis')(ex ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

Ensuring the vue carousel component stops rendering once all of its data has been displayed

Is it possible to stop rendering a vue carousel component once its data is displayed or after a certain amount of time? I've searched for information on this, but haven't found anything relevant. Despite it being an unusual request, I still want ...

Colorful D3.js heatmap display

Hello, I am currently working on incorporating a color scale into my heat map using the d3.schemeRdYlBu color scheme. However, I am facing challenges in getting it to work properly as it only displays black at the moment. While I have also implemented a ...

Element that emulates a different element in HTML

Is it possible to have one element that can control and change multiple clone elements, mimicking every change made to the original? While JavaScript & jQuery can easily achieve this, most solutions involve separate variables or instances for each element ...

Tips on eliminating certain text from a hyperlink

I need assistance with removing the text  Title from my link while preserving the image. <tr id="group0"> <td colspan="100" nowrap="" class="ms-gb"> <a href="javascript:" onclick="javascript:ExpCollGroup('28-1_', ...

Increase or decrease values in an input field using Vue3 when typing

I am looking to implement a feature where users can input numbers that will be subtracted from a fixed total of 100. However, if the user deletes the input, I want the difference to be added back to the total of 100. Despite my attempts, the subtraction wo ...

How to send arguments to an external JavaScript file with JavaScript

In the header of my HTML document, I have included the following script: <script src="http://www.domain.com/js/widgets.js" type="text/javascript"></script> This script references: widgets.js (function () { var styleEl = document.create ...

What differences occur in JavaScript when the IE Developers Tools are accessed?

When the IE Developers Tools are opened, what changes in terms of running an AJAX application? I am currently investigating a mysterious bug related to PrimeFaces dropdown lists in Internet Explorer. Sometimes these dropdowns do not open when clicked, but ...

Ar.js results in objects experiencing deformation or modification when manipulated

Recently, I started experimenting with Ar.js and encountered an issue where the objects displayed on the screen seemed distorted. To illustrate this problem, let me share a basic A-Frame example featuring a perfectly round sphere: <!DOCTYPE> <html ...

Incorporate JSON when adding a new row to the database using Ruby On Rails

Greetings, fellow developers! I am currently working on an application with a backend in Rails. My goal is to create a user from an AJAX request and have the server return a JSON object containing the newly saved user information. Below is my Rails code s ...

Uploading files with Vue.js Element-UI and axios triggers unwanted page refresh

I am utilizing the element-ui file upload component() to manage the frontend of image uploading. All functionalities work flawlessly (file is successfully sent to the server, etc). However, for some reason, after the axios's successful response code r ...

Activate a drop-down feature to refresh the page with a link attached

When I click on a different language, the drop down does not change to that specific language. My code was functioning properly until I added an href attribute to it. Here, you can see my JavaScript function which handles the language selection logic: $(d ...

Discovering the specific value within an array of various objects through Angular

Within a list of objects, I am specifically looking to extract the name "sample 4" from the second set of objects with an ID of 2. How can this value be retrieved using JavaScript or Angular? {Id: 1, name: sample 1, code: "type", order: 1} {Id: 1, name: ...

Tracking global click events in Vue.js can provide valuable insights into user interactions on your

While working with JavaScript, I was able to create this code for a popover. By clicking on the navbar-link element, the popover will appear or disappear. However, it would be great if I could close the popover by clicking anywhere on the screen (when the ...