Troubleshooting issues with calculator operators in JavaScript for beginners

As a beginner in JavaScript, I've taken on the challenge of building a calculator to enhance my skills. However, I'm having trouble getting the operator buttons (specifically the plus and equal buttons) to function properly. Can someone please assist me in making them work as expected?

I am specifically struggling with converting strings into actual numbers using the plus and equal operators to achieve the correct result. For example, when trying to calculate 12 + 12, instead of getting 24, I end up with 12 + 12. I've attempted using methods like eval() and Number() to convert the string to a number, but nothing seems to be working. I've tried various approaches without success.

"use strict";
// Code snippet for a simple calculator
@import url("https://fonts.googleapis.com/css2?family=Nunito+Sans&display=swap");
// CSS styling for the calculator layout
<!DOCTYPE html>
<html lang="en">
// HTML structure of the calculator
</html>

Answer №1

I made the following additions:

currentInput = eval(fullExpression)
screen.textContent = currentInput

and it is functioning perfectly.

"use strict";

// ===============NUMBERS
const screen = document.querySelector(".screen");
const zero = document.querySelector(".zero");
const one = document.querySelector(".one");
const two = document.querySelector(".two");
const three = document.querySelector(".three");
const four = document.querySelector(".four");
const five = document.querySelector(".five");
const six = document.querySelector(".six");
const seven = document.querySelector(".seven");
const eight = document.querySelector(".eight");
const nine = document.querySelector(".nine");
const buttons = document.querySelectorAll(".buttons");

// ==============OPERATORS
const dot = document.querySelector(".dot");
const equal = document.querySelector(".equal");
const plus = document.querySelector(".plus");
const minus = document.querySelector(".minus");
const multiplication = document.querySelector(".multiplication");
const division = document.querySelector(".division");
const clear = document.querySelector(".clear");
const openParenthesis = document.querySelector(".open-parenthesis");
const closeParenthesis = document.querySelector(".close-parenthesis");

// ACTUAL COMPUTING CALCULATOR
let currentInput = "";
let fullExpression = "";
let result = "";

three.addEventListener("click", function() {
  currentInput += "3";
  screen.textContent = currentInput;
  console.log(currentInput);
});
one.addEventListener("click", function() {
  currentInput += "1";
  screen.textContent = currentInput;
});
two.addEventListener("click", function() {
  currentInput += "2";
  screen.textContent = currentInput;
});
plus.addEventListener("click", function() {
  fullExpression = fullExpression + currentInput + " +";
  currentInput = " ";
  console.log(
    `Current input: ${currentInput}`,
    `Full expression: ${fullExpression}`
  );
  /* screen.textContent = fullExpression; */
});
equal.addEventListener("click", function() {
  console.log('eq')
  fullExpression = fullExpression + currentInput;
  console.log(fullExpression);
  currentInput = eval(fullExpression)
  screen.textContent = currentInput
  /* screen.textContent = fullExpression; */
});
clear.addEventListener("click", function() {
  currentInput = "";
  fullExpression = "";
  screen.textContent = "";
});

// Button click
/* buttons.forEach(function (button) {
  button.addEventListener("click", function () {
    const buttonClicked = true;
    console.log(buttonClicked);
  });
}); */
/* two.addEventListener("click", function () {
  screen.textContent += "2";
});
three.addEventListener("click", function () {
  screen.textContent += "3";
});
four.addEventListener("click", function () {
  screen.textContent += "4";
});
five.addEventListener("click", function () {
  screen.textContent += "5";
});
six.addEventListener("click", function () {
  screen.textContent += "6";
});
seven.addEventListener("click", function () {
  screen.textContent += "7";
});
eight.addEventListener("click", function () {
  screen.textContent += "8";
});
nine.addEventListener("click", function () {
  screen.textContent += "9";
}); */
@import url("https://fonts.googleapis.com/css2?family=Nunito+Sans&display=swap");

/*=========================================
     =================RESETS===================
    =========================================== */

*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  min-height: 100vh;
  background-color: black;
  font-family: "Nunito Sans", sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.container {
  width: 400px;
  /*  background-color: red; */
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: 150px;
  grid-auto-rows: 80px;
  gap: 5px;
  padding: 1em;
}

.buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
}

.buttons:hover {
  transform: scale(0.95);
}

.orange {
  background-color: orange;
}

.soft {
  background-color: rgb(143, 143, 143);
}

.dark {
  background: rgb(66, 66, 66);
}


/* ========BUTTONS====== */

.screen {
  grid-column: 1 / 5;
  display: flex;
  justify-content: end;
  align-items: end;
  padding: 1em 2em;
  font-size: 2rem;
}


/* FIRST ROW */

.open-parenthesis {
  grid-column: 2 / 3;
  grid-row: 2 / 3;
}

.close-parenthesis {
  grid-column: 3 / 4;
  grid-row: 2 / 3;
}

.clear {
  grid-row: 2 / 3;
  grid-column: 1 / 2;
}

.division {
  grid-row: 2 / 3;
  grid-column: 4 / 5;
}


/* SECOND ROW */

.multiplication {
  grid-row: 3 / 4;
  grid-column: 4 / 5;
}


/* THIRD ROW */

.minus {
  grid-row: 4 / 5;
  grid-column: 4 / 5;
}


/* FOURTH ROW */

.plus {
  grid-row: 5 / 6;
  grid-column: 4 / 5;
}

.dot {
  grid-row: 6 / 7;
  grid-column: 3 / 4;
}


/* FIFTH ROW */

.zero {
  grid-column: 1 / 3;
}

.equal {
  grid-column: 4 / 5;
  grid-row: 6 / 7;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="styles.css" />
  <title>Calculator</title>
</head>

<body>
  <div class="container">
    <div class="screen dark"></div>
    <div class="buttons one dark">1</div>
    <div class="buttons two dark">2</div>
    <div class="buttons three dark">3</div>
    <div class="buttons four dark">4</div>
    <div class="buttons five dark">5</div>
    <div class="buttons six dark">6</div>
    <div class="buttons plus orange">+</div>
    <div class="buttons minus orange">-</div>
    <div class="buttons multiplication orange">x</div>
    <div class="buttons division orange">÷</div>
    <div class="buttons equal orange">=</div>
    <div class="buttons dot dark">.</div>
    <div class="buttons clear soft">C</div>
    <div class="buttons seven dark">7</div>
    <div class="buttons eight dark">8</div>
    <div class="buttons nine dark">9</div>
    <div class="buttons zero dark">0</div>
    <div class="buttons open-parenthesis soft">(</div>
    <div class="buttons close-parenthesis soft">)</div>
  </div>
  <script src="script.js"></script>
</body>

</html>

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

Tips for utilizing 'toHaveClass' to find a partial match in Jest?

When I assign the class success to an element, React-Mui appends additional text to it in the DOM, such as mui-AbcXYZ-success. This causes my test using the code snippet below to fail: expect( getByTestId('thirdCheck')).toHaveClass("success ...

Leverage environment variables in React JS to define distinct API URLs for production and development environments

For my React app, I started with create-react-app as the boilerplate. To make a request to my local server, I'm using fetch. fetch("http://localhost:3000/users") .then(function(res){ return res.json() }) .then(function(res){ return res.data }) ...

`Is there a specific location for this code snippet?`

Recently, I stumbled upon a script that enables website screen scraping. For instance, you can check out an example on JsFiddle The issue arises when I attempt to incorporate another script from "Embed.ly" This specific script enhances a provided link and ...

Send users from the web (using JavaScript) to the Windows Phone app, and if the app is not installed, direct them

In the following code snippet, I am using angular.js to detect the mobile platform and redirect to the native app. If the app is not installed, it will redirect to the market: $scope.isMobile = { Android: function() { return navigator.userAgent.ma ...

Nested pages are causing jQuery plugins to malfunction

I am currently working on a website, but I am facing some issues with the product listing pages and the tips and tricks page. It appears that there is an issue with jMenu and jFlipBook plugins not functioning properly. Since I didn't develop the origi ...

Tips on managing the onKeyUp event in a ReactJS form

Here is a simple JavaScript function called numericOdds implemented in home.js file: function numericOdds(e) { var valid = /^[1-9]{1}[0-9]{0,1}$/ var number = /^[1-9]{1}$ | ^[1-9]{1}[0-9]{1}$/ var lastValid = ''; var n; console.log(&apo ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

CKEditor5: Unable to access the 'pluginName' property because it is undefined

I am facing a challenge in creating a custom image plugin for CKEditor that can seamlessly integrate with my own image upload system. While trying to set up this plugin, I encountered some difficulties. Oddly enough, the "out-of-the-box" plugins work perfe ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

Is it possible to incorporate an external javascript file in my CSS file?

Currently, I am attempting to create a setup where my background adjusts based on the width of the user's browser. However, I am constrained by a background specified in the external stylesheet under a specific element. While I have the ability to alt ...

Guide on implementing a globalThis polyfill within a NextJS application

Having some trouble with the Mantine react component library on older iOS versions. It's throwing a ReferenceError: Can't find variable: globalThis I've looked into polyfills, but I'm struggling to figure out how to integrate it into ...

Tips for delaying the evaluation of an <input> field?

I am interested in analyzing the content of an <input> field when there is no activity from the user. One simple example I have considered is counting the number of characters, but the actual analysis process is very resource-intensive. To optimize ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

Troubleshooting jQuery Dropdown Menu Animation Bugs

Take a look at this interesting fiddle: https://jsfiddle.net/willbeeler/tfm8ohmw/ HTML: <a href="#" class="roll-btn">Press me! Roll me down and up again!</a> <ul class="roll-btns"> <li><a href="#" class="control animated noshow ...

Strange behavior is observed when using ng-view inside ng-controller, especially when refreshing the

Here is the code I am working with: <body ng-controller="CoreCtrl"> <div ng-cloak> <!-- NavBar --> <div ng-include="'/app/core/navbar.html'"></div> <!-- Main content --> <div class="con ...

"Encountering an issue with the Foreach function in nextjs when iterating through

I attempted to iterate through each character in a String, but the SPANS are not displaying. What could I be doing incorrectly? export default function Work() { const logoText = "The future starts here."; return ( <div className=& ...

What is the reason why modifying a nested array within an object does not cause the child component to re-render?

Within my React app, there is a page that displays a list of item cards, each being a separate component. On each item card, there is a table generated from the nested array objects of the item. However, when I add an element to the nested array within an ...

Learn how to implement a call to 'next()' in Express and Node.js only after successfully creating schemas

I am currently developing an event app, and within my 'Event' schema, I have an array of 'Tag' schemas, allowing each event to be associated with one or more tags. Event: var EventSchema = new Schema({ ... tags: [{ type: Schema.Type ...

retrieve Excel document via POST request

I have a scenario where my API endpoint accepts JSON input and returns an Excel file directly instead of providing a link to download the file. How can I use JQuery AJAX to download this file? Here is the backend code snippet: public function postExcel() ...