Creating a custom calculator using Javascript

As a beginner in Javascript, I am seeking assistance in creating a simple calculator that can add numbers as buttons are clicked and display the running total.

For example: If I click the button "20," it should display the number 20. Then, if I click the button "5," it should display the total of 25, and so on.

Here is the basic code I have managed to put together so far:

<form name="Calc">
<input type="text" name="Numbers" size="16"><BR>
<input type="button" value="  5  " onClick="document.Calc.Numbers.value += '5'">
<input type="button" value="  10  " onClick="document.Calc.Numbers.value += '10'">
<input type="button" value="  20  " onClick="document.Calc.Numbers.value += '20'">
<input type="button" value="  30  " onClick="document.Calc.Numbers.value += '30'">
<input type="button" value="  50  " onClick="document.Calc.Numbers.value += '50'">
</form>

Answer №1

I have identified two main issues with your current implementation:

  1. You have enclosed your numbers within single quotes in the onClick handlers ('5' instead of 5). This leads to string concatenation instead of addition.

  2. The value property of form elements is always treated as a string. Even after resolving the first issue, you still perform string concatenation because JavaScript treats numbers added to strings as concatenation. To address this, you need to parse the values in Numbers before performing addition. For a simple fix in your current project, you can prepend a + to coerce them into numbers:

    document.Calc.Numbers.value = +document.Calc.Numbers.value + theNumberToAdd
    

Below is an example incorporating these two changes:

<form name="Calc">
<input type="text" name="Numbers" size="16"><BR>
<input type="button" value="  5  " onClick="document.Calc.Numbers.value = +document.Calc.Numbers.value + 5;">
<input type="button" value="  10  " onClick="document.Calc.Numbers.value = +document.Calc.Numbers.value + 10;">
<input type="button" value="  20  " onClick="document.Calc.Numbers.value = +document.Calc.Numbers.value + 20;">
<input type="button" value="  30  " onClick="document.Calc.Numbers.value = +document.Calc.Numbers.value + 30;">
<input type="button" value="  50  " onClick="document.Calc.Numbers.value = document.Calc.Numbers.value 50;">
</form>

However, I would recommend a different approach:

  1. Organize your JavaScript code in a separate JavaScript file or a script block within the same file.

  2. Utilize a JavaScript variable to store your current value.

  3. Attach a single click handler to the form to take advantage of event bubbling from descendant elements to ancestors.

Here is an alternative implementation:

// A scoping function to avoid global variables
(function() {
  // Current value
  var value = 0;
  
  // Select the form
  var form = document.querySelector("form[name=Calc]");

  // Set the initial display of the value
  form.Numbers.value = value;
  
  // Add the click handler
  form.addEventListener(
    "click",
    clickHandler,
    false
  );

  // Handle clicks
  function clickHandler(event) {
    var amount;
    
    // Is the click on an input element?
    if (event.target && event.target.tagName.toUpperCase() === "INPUT") {
      // Obtain the input value as a number
      amount = +event.target.value;
      
      // Add it to the total value
      value += amount;
      
      // Display the result
      form.Numbers.value = value;
    }
  }
})();
<form name="Calc">
<input type="text" name="Numbers" size="16"><BR>
<input type="button" value="  5  ">
<input type="button" value="  10  ">
<input type="button" value="  20  ">
<input type="button" value="  30  ">
<input type="button" value="  50  ">
</form>

The above code may seem verbose due to the explanatory comments included.

Answer №2

Here is a basic demonstration. Since there was no provided JavaScript, I included my own:

window.Calc = {
  Numbers: {
    value: 0
  }
};

document.onclick = function () {
  document.getElementById('display').value = Calc.Numbers.value;
}
<form name="Calc">
  <input id="display" type="text" name="Numbers" size="16">
  <BR>
  <input type="button" value="5"  onclick="window.Calc.Numbers.value  += 5"/>
  <input type="button" value="10" onclick="window.Calc.Numbers.value += 10"/>
  <input type="button" value="20" onclick="window.Calc.Numbers.value += 20"/>
  <input type="button" value="30" onclick="window.Calc.Numbers.value += 30"/>
  <input type="button" value="50" onclick="window.Calc.Numbers.value += 50"/>
</form>


Reasoning

In JavaScript, there are Strings and Numbers. Strings cannot be directly added. By removing the quotes, the additions should function correctly.


Preferred Approach

I suggest avoiding inline JavaScript. Take a look at this demo, it simplifies the process of adding new numbers.

Fiddle

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

Attempting to access a variable from outside the function

I am looking to pass the index variable from mapping to the event change function in my code snippet below: {this.data && this.data.map((item, index) => ( <tr className="table-info" key={index}> <td>{index}</ ...

Dividing the logic from the Express router while retaining the ability to utilize Express functionalities

As I embark on my journey of developing my first app using Node.js and Express, I have noticed that my router file is starting to get overcrowded with logic. It seems like there is too much going on in there. My solution to this issue is to pass a functio ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...

Generating grid-style buttons dynamically using jQuery Mobile

I am in need of assistance to create a dynamic grid using jQuery Mobile. The grid should consist of buttons with either 'onclick' or 'href' functionality. The number of buttons should be generated dynamically at runtime. Specifically, I ...

Encountering an error while attempting to load the jQuery script: TypeError - $.fn.appear.run is not a

I have included an animation script for CSS in my markup, but I am encountering the following error: TypeError: $.fn.appear.run is not a function Does anyone know why this is happening and how I can resolve it? /* * CSS3 Animate it * Copyright (c) 2 ...

Node.js and MongoDB integration for implementing like and dislike buttons

I have been struggling to create a system for liking and disliking posts in my project. The issue I am facing is with the communication between the server and client side. Here is the form I am using: https://i.sstatic.net/IBRAL.png When I click on the li ...

Utilizing Browserify routes and configuring Webstorm

When building my project using gulp and browserify, I made use of path resolution for easier navigation. By following this guide, I configured browserify as shown below: var b = browserify('./app', {paths: ['./node_modules','./src ...

Executing a function within the same file is referred to as intra-file testing

I have two functions where one calls the other and the other returns a value, but I am struggling to get the test to work effectively. When using expect(x).toHaveBeenCalledWith(someParams);, it requires a spy to be used. However, I am unsure of how to spy ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

Issue with the demo code for Vue Stripe Checkout

As I delve into the world of Vue-Stripe-Checkout, I encountered a snag right from the start with the demo code provided. The issue arises when utilizing the Vue Stripe Elements component. Has anyone else experienced this problem? There are no errors displa ...

Navigating with Link in React Router DOM v5 to successfully pass and catch data

In the process of developing a basic chat application, I encountered an issue with passing the username via the Link component. Below is the relevant code snippet: <Link to={{ pathname: `/${room}`, state: { the: user } }}> Enter room </Link> ...

Ways to smoothly conclude a loading animation in real-time

I have a unique challenge of creating a loading animation using Adobe After Effects instead of CSS. The main goal is to develop an animation that continuously loops, but when the loading process stops, it ends with a distinct finishing touch. For instance, ...

Importing a JavaScript file into another JavaScript file as text in React Native can be a convenient way

In my project, I have a file named MyFirstPage.js that contains the following code snippet: renderCards() { let icon = this.state.icon; .... .... .... } This code is responsible for rendering cards within the main render function. However, as the ...

Steps to creating an elliptical border using CSS

Is there a way to apply CSS styles specifically to the left border of a div to achieve an elliptical shape, while keeping other borders normal? I've managed to create a semi-ellipse with the following code, but the rest of the border remains unchanged ...

Populating a Listview in jqueryMobile with dynamic elements

I am struggling with my listview. Whenever I try to add or remove items from the list, the jquery mobile styling does not get applied to the new content that is added. <ul data-role="listview" id="contributionList"> <li id="l1"><a>5. ...

Mastering parameter passing in Node.js functions: A comprehensive guide

As I embark on my journey with node js (refer to the question), please be patient as I navigate through this new territory. To clarify my query, I have developed a function to be invoked in another JS file: exports.test = function(req, res){ connection ...

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

Using OPTIONS instead of GET for fetching Backbone JS model data

Currently, I am attempting to retrieve data from a REST endpoint with the help of a model. Below is the code snippet that I am using: professors: function(id) { professor = new ProfessorModel({ id: id }); professor.fetch({ headers: { ...