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

What is the best way to show an array within a string using javascript?

Take a look at this code snippet : const names = ["Alex", "John", "Kit", "Lenny"]; for(let i = 0; i < 4; i++) { $("body").append("<p>" + names[i] + "</p>'); }; Can you figure out how to dynamically add each item in the 'names&a ...

Error message "Script start is missing" found in install.json for socket.io-php package

I am looking to develop a .io game that integrates with some PHP APIs, and I have been attempting to run the following files: install.json: { "name" : "workerman/phpsocket.io", "type" : "library", "keywords": ["socket.io"], "homepage": ...

The ng-repeat function is not functioning properly when used within an li element to trigger

I have utilized the Dialog service to create a pop-up window. My intention is to display a message to the user in this format: txt = '<ul> <li data-ng-repeat = "eachValue in dummnyList" > {{eachValue | applyFilte ...

Implementing JavaScript to Activate Radio Button on Mouse Click

I am relatively new to JavaScript and I am working on setting up an automator to handle some repetitive tasks on a work website. Today, I have spent several hours trying to use JS to select the second radio button out of two. I thought the following code s ...

Incorporate communication between the front-end and backend

I encountered an error while attempting to import the getUser function in my backend code. The actual function is located in the frontend at ../utils/auth. How can I successfully import between front-end and backend? Or might there be another issue at pla ...

Using a local variable with jquery getJSON: A comprehensive guide

I am looking to expand the autocomplete capabilities of Ace Editor and I require a JSON file containing words. Here is my code snippet: function load_completions() { var object = $('#preview').attr('class'); $.ajax({ ...

Unable to retrieve $wpdb, returning as null

In my development process, I am working on a basic plugin using the Wordpress Plugin Boilerplate. I have implemented AJAX to create an action triggered by a button press to remove an item from a custom database table I have set up. The AJAX function, butto ...

Angular UI-Select's issue with duplicating tags while adding objects for tagging functionality

I have implemented the ui-select library to enable the "Tagging" feature in my project. Currently, I am utilizing an Array of objects where each object contains an id and a name. The functionality is working as expected. However, when a user types in a n ...

Having issues with the $addToSet method in my MongoDB API implementation

Despite searching through various topics, I couldn't find a solution to my specific problem. In an effort to enhance my JavaScript skills, I embarked on creating a quote generator. I successfully developed the API and frontend components. However, c ...

What are the steps for integrating an external API into a React project?

Apologies for any potential repetition, as this question may be commonly asked. I am currently working with React, Express, CORS, node, and postgres databases. My objective is to utilize the following API to retrieve real-time prices for metals: https://me ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...

"Troubleshooting an issue with ng-model not functioning properly with radio buttons in Angular

I'm a newcomer to Angular and I'm attempting to retrieve the value of the radio button selected by the user using ng-model. However, I'm not seeing any output in "selected contact". Check out My HTML below: <!doctype html> <html n ...

GAS: What strategies can I implement to optimize the speed of this script?

I have a sheet with multiple rows connected by "";" and I want to expand the strings while preserving the table IDs. ID Column X: Joined Rows 01 a;bcdfh;345;xyw... 02 aqwx;tyuio;345;xyw... 03 wxcv;gth;2364;x89... function expand_j ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResul ...

Is it necessary for JavaScript functions to be stored in a separate file in order to be invoked?

Here is the scenario that unfolded: Within a .php file, I had the following form: <form action="/flash_card/scripts/create_user_gate.php" onsubmit="return validateForm()" method="post"> <table align="center"> ...

Serve different files using Node.js socket.io webserver, not just index.html

I recently started delving into socket.io and decided to use this chat example as a reference. As I navigate to ip:8080/public/index.html, I realize the need to access other files, such as additional JS scripts that will be used on the client side in the ...

Tips for developing an npm package that includes a demonstration application

When creating packages, I believe it's important to include a demo app. However, I'm unsure about the best way to organize the file structure for this purpose. My goal is to have one Github repository containing both my published NPM module and ...

Is there anyone available to assist me with this contact validation form?

I'm struggling to make this contact form highlight red and display 'not valid' inside the boxes. Despite my efforts, I just can't seem to get it to work! I'm unable to change the existing HTML tags, but I can add to the HTML. I wan ...

Creating a shared function using TypeScript

Having a vue3 component that displays a list of items and includes a function to delete an item raises a concern about checking parameters and specifying the array for the filter operation. The goal is to create a universal function using typescript. <t ...