Pressing the reset button on a basic calculator

I am experiencing an issue with my calculator. It works fine initially, but after using the reset button, it stops functioning properly. Currently, I only have the multiplication set up as I debug this problem. I am new to JavaScript and would appreciate any assistance.

Below is my HTML code:

var input = "";
var firstInput = "";
var secondInput = "";
var answer = "";

$(".numbers").click(function(){
  $("#topBar").text(input += $(this).text())
});

function operation() {
  firstInput = input;
  $("#topBar").empty();
  $(".numbers").click(function(){
    $("#topBar").text(secondInput += $(this).text())
  });
}

$("#buttonx").click(function(){
  if(input !== ""){
    operation();
  }
});

$("#buttonEqual").click(function(){
  answer = firstInput * secondInput;
  $("#topBar").text(answer);
});

$("#resetButton").click(function(){
  input = "";
  firstInput = "";
  secondInput = "";
  answer ="";
  $("#topBar").empty(); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="container">
  <div id="topBar"></div>
  <div class="row">
    <div class="butStyle">
      <button class="numStyle numbers" id="button7">7</button>
    </div>
    <div class="butStyle">
      <button class="numStyle numbers" id="button8">8</button>
    </div>
    <div class="butStyle">
      <button class="numStyle numbers" id="button9">9</button>
    </div>
    <div class="butStyle">
      <button class="numStyle operation" id="buttonDivide">&divide;</button>
    </div>
  </div>
  <div class="row">
    <div class="butStyle">
      <button class="numStyle numbers" id="button4">4</button>
    </div>
    <div class="butStyle">
      <button class="numStyle numbers" id="button5">5</button>
    </div>
    <div class="butStyle">
      <button class="numStyle numbers" id="button6">6</button>
    </div>
    <div class="butStyle">
      <button class="numStyle operation" id="buttonx">x</button>
    </div>
  </div>
  <div class="row">
    <div class="butStyle">
      <button class="numStyle numbers" id="button1">1</button>
    </div>
    <div class="butStyle">
      <button class="numStyle numbers" id="button2">2</button>
    </div>
    <div class="butStyle">
      <button class="numStyle numbers" id="button3">3</button>
    </div>
    <div class="butStyle">
      <button class="numStyle operation" id="buttonMinus">-</button>
    </div>
  </div>
  <div class="row">
    <div class="butStyle">
      <button class="numStyle numbers" id="button0">0</button>
    </div>
    <div class="butStyle">
      <button class="numStyle numbers" id="buttonDot">.</button>
    </div>
    <div class="butStyle">
      <button class="numStyle" id="buttonEqual">=</button>
    </div>
    <div class="butStyle">
      <button class="numStyle operation" id="buttonAdd">+</button>
    </div>
  </div>
  <button id ="resetButton">Reset</button>
</div>

Answer №1

The issue arises from repeatedly registering a new click listener each time an operator is pressed:

$(".numbers").click(function(){
  $("#topBar").text(secondInput += $(this).text())
});

To address this problem without fundamentally changing the logic (although I would suggest refactoring many aspects), it's important to ensure that this code block is not executed if it has already been triggered.

Answer №2

Using the empty() function will clear out all child nodes from the selected element. You may consider replacing the content with a different value, such as an empty string or zero, or utilizing the html() function as an alternative.

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

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...

Tips for improving the loading speed of my website

What are the best ways to improve website optimization and increase page speed? I have already minified JavaScript and CSS, as well as optimized images, but Google continues to penalize our pages. Any suggestions? ...

Best practices for remotely monitoring and managing a server in real-time using HTTP

Looking to view server CPU, RAM, and HDD stats along with gathering info from various logs on my client device (a phone with a browser). Implementing ajax polling. Every 5 seconds, setInterval is used on the client to call a PHP file: Scan a folder c ...

Alert: Github Dependabot has flagged Babel as vulnerable to arbitrary code execution when compiling meticulously designed malicious code

My Github Repository's Security section is flagging this issue as Critical for both my Frontend and Backend code. I'm having trouble grasping the nature of this alert. Can someone explain what flaw it represents? After updating my dependencies, ...

What's the best way to update the fill color of an SVG dynamically?

Is it possible to change the color of an SVG image dynamically without using inline SVG tags? I want to create a code that allows users to specify the source for the SVG tag and a hexadecimal color value, enabling them to customize any SVG image with their ...

How can I identify when a node/express ajax request is received?

I have set up a node/express server that sends the ajax-start.html file. Within this file, there is a script that enables ajax requests to be made to the server. Everything functions correctly in this setup. However, I am looking to enhance this process by ...

Struggling three.js newcomer faced with initial hurdle: "Function is undefined"

I am encountering a similar issue to the one discussed in this question: Three.js - Uncaught TypeError: undefined is not a function -- and unfortunately, the solutions provided there did not work for me. My journey with three.js began on the Getting Start ...

The use of @font-face in CSS seems to be malfunctioning

I am having trouble changing the font in my CSS to what I want it to be. body{ background-color:#a8a7a7; color:#C50909; font-family: main, Calibri; text-align:center; } @font-face{ font-family: main; src: url('fonts/RegencieLight.ttf'); } ...

Scroll down 1 page using Javascript and Jquery

Hey there! I'm looking to create a website where a small scroll on the mouse wheel will take the site to the next anchor. It's kind of hard to explain, but one good example is the Tesla Model 3 website on the US site here. Does anyone have any t ...

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...

What is the best way to target an HTML element that is only connected to a particular class?

My HTML code includes the following 3 elements: <span class="a b"></span> <span class="a"></span> <span class="a b"></span> I am trying to select the element that only has the class "a". When I use $("span.a"), it sele ...

Enhance your browsing experience with the Firefox Extension "PageMod," a powerful script

In the process of developing my Firefox extension, I am attempting to dynamically create a global function: window.performAction= function() { ... }; After further investigation, I have discovered that the window is encapsulated by an XrayWrapper. windo ...

Guide on adjusting the darkness of a MaterialUI Avatar component image and adding text to it

I'm currently working with the Avatar component from Material UI along with Tailwind CSS. I found that by simply adding the image URL to the src, it displays the avatar successfully. <Avatar alt="Cindy Baker" src="https://mui.com/sta ...

Tips for integrating Material UI Drawer with Redux

I have been attempting to incorporate a Drawer feature that displays on the left side while utilizing Redux to maintain the state of the Drawer. Unfortunately, I seem to have made an error as my onClick events are not responsive. Here is the code: Reduce ...

Error: Cannot set value on a property that is designated as a getter-only in Vue.js using

My current task involves taking an image as input, converting it into a base64 string, preparing a payload containing the base64 string, and sending a post request to the backend. I then need to retrieve the response data and preview the base64 image from ...

Creating fluid designs for my boxes with CSS to enhance responsiveness

I have designed my HTML file with 8 boxes that appear correctly on desktop, but when viewed on mobile devices, the columns are misaligned and shifted to the right side instead of being centered. How can I make it more responsive? See Preview Here is the ...

Unable to set two image layers on HTML canvas to display in different colors as anticipated

I am facing a challenge with stacking 3 images: an outline, a white base, and a pattern that is also white. My goal is to layer these images where the base is at the bottom with one color assigned to it, the pattern is stacked on top with a different color ...

What is the most effective method for tracking file upload progress using SSE?

I am currently working on creating a file upload progress feature that is compatible with older browsers using AJAX. In HTML5, there is the xhr.upload.progress event which works well for modern browsers, but I need an alternative for non-XHR2 browsers. I h ...

a hyperlink not functioning properly after the # symbol

I’ve been attempting to obtain the URL in order to share it on Google Plus. I’ve experimented with different codes, but the issue is that the ID value is concealed within the URL, making it impossible to directly pass the link in the "a href" tag. The ...

Discover how to access the return object in jQuery

Discover How to Access Return Object in JQuery 4 minutes ago|LINK I've developed a WCF service that returns a GenericList Object. I'm struggling to retrieve this object on the client side using jQuery: Here's my code snippet: WCF Service ...