JavaScript Calculator experiencing difficulty with adding two numbers together

I've been working on developing a calculator using HTML and JavaScript, but I'm facing an issue when trying to add two numbers together. Strangely enough, when attempting to calculate 1 + 0, I get the result of 512, and for 1 + 1, it returns 1024. I even attempted dividing the final result by 512 with no success for larger numbers. I've searched for a solution online, but I can't seem to find the exact problem.

var val = 0;
var op = "";

function calculate(clicked_id) {
  var buttonID = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  for (var i = 0; i < buttonID.length; i++) {
    if (clicked_id == buttonID[i]) {
      document.getElementById("input").value += clicked_id;
      break;
    } else if (clicked_id == "add") {
      val = parseInt(document.getElementById("input").value);
      document.getElementById("input").value = "";
      op = "plus";
      break;
    } else if (clicked_id == "equal") {
      var temp = parseInt(document.getElementById("input").value);
      document.getElementById("input").value = "";
      if (op == "plus") {
        val += +temp;
        document.getElementById("input").value = String(val);
      }
    }
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="script.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

  <title>Bootstrap</title>
</head>

<body>

  <div class="jumbotron jumbotron-fluid">
    <div class="container">
      <h1>Calculator</h1>
     <p>Created by Nabil</p>
    </div>
  </div>

  <div class="form-group">
    <input type="text" id="input" placeholder="">
  </div>

  <div class="btn-group" role="group" aria-label="Basic example">
    <button type="button" class="btn btn-dark" id="0" onclick="calculate(this.id)">0</button>
    <button type="button" class="btn btn-light" id="1" onclick="calculate(this.id)">1</button>
    <button type="button" class="btn btn-light" id="2" onclick="calculate(this.id)">2</button>
    <button type="button" class="btn btn-light" id="3" onclick="calculate(this.id)">3</button>
    <button type="button" class="btn btn-light" id="4" onclick="calculate(this.id)">4</button>
    <button type="button" class="btn btn-light" id="5" onclick="calculate(this.id)">5</button>
    <button type="button" class="btn btn-light" id="6" onclick="calculate(this.id)">6</button>
    <button type="button" class="btn btn-light" id="7" onclick="calculate(this.id)">7</button>
    <button type="button" class="btn btn-light" id="8" onclick="calculate(this.id)">8</button>
    <button type="button" class="btn btn-light" id="9" onclick="calculate(this.id)">9</button>
    <button type="button" class="btn btn-secondary" id="add" onclick="calculate(this.id)">+</button>
    <button type="button" class="btn btn-secondary" id="equal" onclick="calculate(this.id)">=</button>
  </div>
</body>

</html>

Answer №1

Make sure to include a break statement in the last else if block.

var val = 0;
var op = "";

function calculate(clicked_id) {
  var buttonID = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  for (var i = 0; i < buttonID.length; i++) {
    if (clicked_id == buttonID[i]) {
      document.getElementById("input").value += clicked_id;
      break;
    } else if (clicked_id == "add") {
      val = parseInt(document.getElementById("input").value);
      document.getElementById("input").value = "";
      op = "plus";
      break;
    } else if (clicked_id == "equal") {
      var temp = parseInt(document.getElementById("input").value);
      document.getElementById("input").value = "";
      if (op == "plus") {
        val += +temp;
        document.getElementById("input").value = String(val);
      }
        break;
    }
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="script.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

  <title>Bootstrap</title>
</head>

<body>

  <div class="jumbotron jumbotron-fluid">
    <div class="container">
      <h1>Calculator</h1>
      <p>Designed by Nabil.</p>
    </div>
  </div>

  <div class="form-group">
    <input type="text" id="input" placeholder="">
  </div>

  <div class="btn-group" role="group" aria-label="Basic example">
    <button type="button" class="btn btn-dark" id="0" onclick="calculate(this.id)">0</button>
    <button type="button" class="btn btn-light" id="1" onclick="calculate(this.id)">1</button>
    <button type="button" class="btn btn-light" id="2" onclick="calculate(this.id)">2</button>
    <button type="button" class="btn btn-light" id="3" onclick="calculate(this.id)">3</button>
    <button type="button" class="btn btn-light" id="4" onclick="calculate(this.id)">4</button>
    <button type="button" class="btn btn-light" id="5" onclick="calculate(this.id)">5</button>
    <button type="button" class="btn btn-light" id="6" onclick="calculate(this.id)">6</button>
    <button type="button" class="btn btn-light" id="7" onclick="calculate(this.id)">7</button>
    <button type="button" class="btn btn-light" id="8" onclick="calculate(this.id)">8</button>
    <button type="button" class="btn btn-light" id="9" onclick="calculate(this.id)">9</button>
    <button type="button" class="btn btn-secondary" id="add" onclick="calculate(this.id)">+</button>
    <button type="button" class="btn btn-secondary" id="equal" onclick="calculate(this.id)">=</button>
  </div>
</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 bind a click handler or any event handler to my object or module?

Can someone help me with attaching event handlers to my module in a way that I am not sure how to achieve? Here is the snippet of my module: var globalModule = { name:'Banana on princess bed', init:function(){ alert('Init ...

Enhance Your HTML Skills: Amplifying Table Display with Images

Recently, I utilized HTML to design a table. The Table Facts : In the first row, I included an appealing image. The second row contains several pieces of content. In continuation, I added a third row. The contents in this row are extensive, resulting i ...

Building a Wordpress website with AJAX functionality using only raw Javascript and no reliance on Jquery

So, I have a custom script named related-posts.php, and I want to insert it into posts only when the user scrolls. In addition, I have an enqueued script file in WordPress that loads in the footer, where I have written AJAX code like this: var xmlhttp = ...

Having trouble retrieving XSRF-TOKEN from cookie in Next.js (React.js)?

When working with Next.js and Laravel 8 backend, I encountered an issue where I couldn't set the XSRF-TOKEN generated by Laravel on my fetch request for login. Despite being able to see the token in the inspect element > application tab > cookie ...

How can I modify the content within a scoped `<style>` tag in Vue?

Is there a way to dynamically change the contents of a <style> block in my Vue component using Vue variables? Many commonly suggested solutions involve inline styles or accessing the .style property with JavaScript. However, I am looking for a metho ...

Pinia: Is it better to invoke '{myStore}' or 'return myStore' within the return statement?

I'm currently working on integrating a Pinia store into a component of my Vue app and I'm puzzled by the need to return the store in { } instead of just returning it as is. Can someone clarify the distinction between return {foo} and return foo f ...

Prevent further triggering of the .click function when the user clicks repeatedly

Is there a way to prevent the .click function from executing if the user clicks too many times? This is my current code: $('button').click(function() { $('#bg').fadeToggle('200'); }); Check out the jsfiddle DEMO ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

Navigate through the rows and columns of an HTML table by utilizing Javascript with webdriver, specifically for Protractor in a non-angular environment

I need help with iterating through rows and columns using Selenium Webdriver. I am currently using Protractor for a non-angular web page. I have some Java code that works with the WebElement class to get the number of links, but now I need to transition th ...

Having trouble getting the .push() method in JavaScript to function correctly

I've encountered an issue while trying to develop a function that iterates through each item in an array and records the index of a specific item when found. In this particular function, whenever the item 'contraband' is detected during the ...

Is there a way to eliminate the feature that rearranges characters in reverse order?

Is there a way to modify this code to only replace vowels with "er" instead of reversing the order of characters? I'm hoping to remove the function that reverses the character order. If you want to take a look at the code, it's available on Past ...

Order an array depending on various strings

I am faced with the challenge of reordering a JSON array to mimic a conversation thread structure using Javascript. The initial array looks like this: var all_messages = [{ name: 'user1', replying_to: '', message: 'xxxxx&apo ...

Issue with dropdown menu appearing beneath specific elements in Internet Explorer versions 7 and 8

I've been encountering some troublesome issues with a website I'm working on, specifically in Internet Explorer 7/8. On certain pages, the navigation elements are getting hidden below text and images, causing confusion for me. I've attempted ...

Retrieve the most recently added item in the Material-ui Autocomplete component

Currently, I am incorporating the material-ui Autocomplete component with multiple selection feature. In one specific scenario, I require the ability to retrieve only the value of a newly added item. Despite utilizing the onChange listener, the event pro ...

Accessing Google Maps offline using HTML5 is a convenient and helpful

Our team is working on an HTML5 application that includes a Google map feature for changing search locations. Recently, we've added an offline version of the app as well. Is there a way to cache the Google map so that when the app is offline, it can s ...

NextJS getStaticProps failing to pass fetched data to the page component

Struggling with passing props from getStaticProps function into template pages in NextJS. Below is the code for the dynamic page template that I am using. // src/pages/blog/[slug].js import React from 'react'; import matter from 'gray-matte ...

Issue with JQuery delay functionality not activating correctly upon clicking an <a> tag

When I click on an <a> tag, I want to display a div and wait for 10 seconds before redirecting. However, the div is currently being shown immediately without waiting. Here is the HTML code: <a class="clickHereToDisplay" href="http://www.google.c ...

The React Js error message shows an 'Uncaught (in promise)' TypeError that prevents reading an undefined property

Struggling with passing the response from an Ajax request to another function in React. Although I am able to receive the response, I cannot pass it to { this.showBattersData(data); } where I need to render the DOM. It's clear that something is missin ...

Preventing template rendering in Angular until an event is triggered - but how?

I am currently working on a directive that functions well, but I had to resort to using inline template code in order to delay rendering until the click event occurs. However, I believe it would be more streamlined if I could assign the directive template ...

The function will not be triggered when the form is submitted

I've set up this form to send data to the server-side. It's built in HTML/CSS with AngularJS as well. I made sure that the button is placed inside the form, a common mistake that can cause issues. However, despite my efforts, the function "onAddE ...