What's the best way to ensure that all the numbers I input into my calculator app are effectively combined when I press the buttons?

For my very first coding project, I decided to create a calculator app. Despite the abundance of tutorials available online, I wanted to challenge myself by breaking down the problem into smaller steps on my own.

However, I've encountered an issue where each button press replaces the previous value with the new one, instead of combining the two values together (e.g., pressing "1" and then "2" should display "12"). I'm struggling to figure out how to program this functionality.

Any suggestions or ideas would be greatly appreciated!

Thank you!

https://codepen.io/tphelps5/pen/GRgBMMZ?editors=1010

JavaScript


let reset = document.getElementById("reset"),
    output = document.getElementById("output"),
    calcButtons = document.getElementById("calc_buttons");

calcButtons.addEventListener("click", printNum, false);

function printNum(e) {
  if (e.target !== e.currentTarget) {
    let clickedItem = e.target.value;
    output.innerHTML = clickedItem;
  }

  e.stopPropagation();
}

HTML

<HTML> 
  <h1> My First JavaScript Calculator </h2>
  <div id="calculator">

  <div id="calc_buttons">
    <span id="output"></span>

    <button class="operate" id="reset" value=" ">C</button>

    <button class="num" id="seven" value="7">7</button>
    <button class="num" id="eight" value="8">8</button>
    <button class="num" id="nine" value="9">9</button>

    <button class="operate" id="divide" value="/">/</button>


    <button class="num" id="four" value="4">4</button>
    <button class="num" id="five" value="5">5</button>
    <button class="num" id="six" value="6">6</button>

    <button class="operate" id="multiply" value="*">*</button>

    <button class="num" id="one" value="1">1</button>
    <button class="num" id="two" value="2">2</button>
    <button class="num" id="three" value="3">3</button>

    <button class="operate" id="minus" value="-">-</button>


    <button class="num" id="zero" value="0">0</button>

   <button class="operate" id="decimal" value=".">.</button>
   <button class="operate" id="equals" value="=">=</button>


   <button class="operate" id="plus" value="+">+</button>

</div>



</HTML>

Answer №1

The following code snippet will replace the content of outer with the value of clickedItem:

output.innerHTML = clickedItem;

Instead, you can try using this code snippet to append the value of clickedItem to the existing content:

output.innerHTML += clickedItem;

(Please note that the + operator appends strings and adds numbers. Be cautious as this might lead to confusing bugs at times.)

Answer №2

How to Combine User Input Numbers

To merge numbers entered by a user, the process is quite simple.

There are two key steps involved:

  1. Keep track of numbers as they are entered and store them when an operator is input
  2. Maintain a comprehensive list of all numbers and operators provided by the user
let arr = []; // contains the sequence of numbers and operators
let str = ""; // current number string
function printNum(e) {
    ...// your custom code logic
    if (e.target.value === "+" || e.target.value === "-" || ...) { // handle all mathematical operators OR use regex matching
        // for OP: Implement logic to handle multiple consecutive operator inputs
        arr.push(str);
        str = "";
        arr.push(e.target.value)
    } else {
        str += e.target.value;
    }
}

The resulting array will have this structure:

 arr = ["12","+","15","*", ...]

Evaluating the array to obtain the final value can be challenging but rewarding.

A Detailed Explanation

The main goal was to present a clear and uncomplicated solution without overcomplicating your code. Before proceeding, please acknowledge the potential risks:

Warning: Using eval() in JavaScript poses significant security threats. It exposes you to malicious code execution. Refer to the Never use eval()! caution below.

Solution:

An easy (yet not recommended) method involves maintaining a string to keep track of user input and applying calculations using eval.

This approach does not address incorrect user inputs like 1+2++3+5+

Basic usage example:

let str = "1+3+5";
let ans = eval(str); // ans equals "6"

As seen here, a correctly formatted string containing mathematical operations will yield the final result when evaluated with eval.

If you are comfortable with this technique, you can simplify the process by:

let str = ""
function printNum(e) {
    ...// your own code logic
    str += e.target.value;
}

I refrained from providing a complete working example to allow you to tackle the remaining challenges on your own. However, if you require a reference, visit this pen.

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

Having trouble seeing the Facebook registration page on Firefox?

Encountering some issues with Facebook and Firefox. Specifically, the registration popup on Facebook always appears empty when using Firefox. I have tried different approaches to the popup code but so far, nothing seems to be resolving the issue. Is there ...

Using Bootstrap 4 to validate credit card information with personalized error messages

How can I apply Bootstrap 4 validation to ensure that the credit card number contains only numbers, is 16 digits long, and display appropriate messages based on user input? I want to display three distinct messages: 1. When no input is provided, show "Cre ...

Deleting a product category along with all its products: Understanding the basics of CRUD操作

I am looking for a way to delete a product category along with all the products within it. The Product model has a reference to the category as an object. Is there a straightforward method or a commonly used technique for this? I attempted to use removeAl ...

how to forward visitors from one URL to another in a Next.js application

I have an existing application that was initially deployed on , but now I want to change the domain to https://example.com. What is the best way to set up redirection for this domain change? I have attempted the following methods: async redirects() { r ...

CSS animation is supported on most browsers with the exception of Safari

I'm facing an issue with my animation that works fine on all browsers except Safari. I've tried using the autoprefix extension in VSCode to automatically add CSS vendor prefixes, but the animation still isn't functioning correctly. Here&apo ...

Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs. Here's an example of how I want it to work: const AsyncComp ...

Is it feasible to capture a screenshot of a URL by using html2canvas?

Is it possible to take a screenshot of a specific URL using html2canvas? For example, if I have the following URLs: mydomain.com/home mydomain.com/home?id=2 mydomain.com/home/2 How can I capture and display the screenshot image on another page? window ...

What types of HTML are compatible with SweetAlert?

I am exploring the HTML elements that can be used with the SweetAlert alert function (). It seems that headings like h1, h2, etc. and strong tags are allowed, but when I tried to add inline styles like style="color:blue;", the alert stopped working. The v ...

Error: Unable to run 'play' on 'HTMLMediaElement': Invocation not allowed

Just a simple inquiry. I am trying to store an HTMLMediaElement method in a variable. // html segment <video id="player" ... /> // javascript segment const video = document.querySelector('#player') const play = video.play video.play() / ...

Switch up the hover color of the dropdown menu in the Bootstrap navbar

I'm struggling to change the hover color of the dropdown menu in the navigation bar. Can anyone please help me with this? Here is my HTML code. How can I change the hover color using CSS? <div class="navbar navbar-inverse" id="menu"> <di ...

Creating dynamic DIV elements in an AngularJS file using data retrieved from a Sql server

I need to dynamically add elements based on data retrieved from a MSSQL server in the specified area: <div id="ApplicationForm" class="tabcontent" style="display:none;"> <div class="tab_section"> ...

Discovering the Data Structures within the d3.js Illustrations by the Talented Mike Bostock

Wondering how to decipher the structure of JSONs in examples by Mike Bostock, like this one (after being transformed using d3): http://bl.ocks.org/mbostock/3886208 I aim to replicate it with my own fabricated array of JSON objects without relying on load ...

Animate the opening and closing of a div element

A form is set up for editing. Within this form, there are 2 separate divs. The first div is labeled editForm, which displays the form for editing, and the second div is labeled infos, which shows the details of this form. My goal is to have the infos se ...

Ensure that three spans are precisely aligned to occupy a single line

My dilemma is as follows: I have a line within a document that has a set width. Now, there are 3 elements involved - one <a> tag and two <span> tags. The content in the <a> tag varies in width each time it appears on the line. The thi ...

Using asp.net MVC along with jQuery and Razor to toggle checkbox selections within a group

I am attempting to toggle the checkboxes within a group. My goal is to click on the corresponding parent (id=50, id=51), and then have all its child checkboxes also be clicked. I have tried using the closest and find jQuery functions with some modification ...

Flex Display with Bootstrap for Responsive Tables

Is there a way to display the scrolling of a Bootstrap table using a flex container? https://getbootstrap.com/docs/4.4/content/tables/#responsive-tables I am looking for the JSFiddle example with DIV elements. Removing the display:flex from .flex_containe ...

"Trouble with 3D hexagonal grid in CSS - unable to achieve desired display

In order to create a dynamic Hexagonal Grid using CSS, the objective is to automatically reorganize hexes in a circular or rectangular manner when a new div with a specific class (e.g. 'hexes') is added to the view. Currently, there is a grid wi ...

JavaScript code to convert a query into an array

Is there a way to search through a JavaScript array to find all names that start with the letter A? If so, how can I display all of the information associated with those names? Name":"Albert","age":"14" Name":"Alison","age":"14" Here is my JSON array: ...

Angular calendar displaying days and dates in a Gantt chart

I am currently navigating the world of AngularJS and I have implemented an Angular Gantt chart from this repository https://github.com/angular-gantt/angular-gantt. However, I noticed that the chart displays dates but it does not display days (Su, Mo, Tu, e ...

Utilizing jQuery for AJAX-Based Deletion of Records

Hey, I stumbled upon a code snippet that allows me to delete a row from my database using Ajax. However, there seems to be an issue where the table that should disappear when deleted is not working properly. Here is the JavaScript code: <script type=" ...