Combining two-digit values

As a newcomer to JavaScript, I've been working on creating a basic calculator to practice my skills. However, I've run into an issue. When entering a double-digit number, the calculator is adding the digits together instead of treating them as separate numbers. For example, inputting 12 + 5 results in the answer 8. I'm struggling to resolve this problem and would appreciate any suggestions or guidance. Thanks for your help! PS: Sorry for the lengthy explanation. `


            </div>
                    <button type="button" onclick="putToScreen(1); xValue += parseInt(1)" class="inputButton1 input" value="1">1</button>
                    <button type="button" onclick="putToScreen(2); xValue += parseInt(2)" class="inputButton1 input" value="2">2</button>
                    <button type="button" onclick="putToScreen(3); xValue += parseInt(3)" class="inputButton1 input" value="3">3</button>
                    <button type="button" onclick="putToScreen('+'); plusButton++" class="inputButton1" value="+">+</button>
                    <button type="button" onclick="putToScreen(4); xValue += parseInt(4)" class="inputButton2 input" value="4">4</button>
                    <button type="button" onclick="putToScreen(5); xValue += parseInt(5)" class="inputButton2 input" value="5">5</button>
                    <button type="button" onclick="putToScreen(6); xValue += parseInt(6)" class="inputButton2 input" value="6">6</button>
                    <button type="button" onclick="putToScreen('-')" class="inputButton2" value="-">-</button>
                    <button type="button" onclick="putToScreen(7); xValue += parseInt(7)" class="inputButton3 input" value="7">7</button>
                    <button type="button" onclick="putToScreen(8); xValue += parseInt(8)" class="inputButton3 input" value="8">8</button>
                    <button type="button" onclick="putToScreen(9); xValue += parseInt(9)" class="inputButton3 input" value="9">9</button>
                    <button type="button" onclick="putToScreen('*')" class="inputButton3" value="*">*</button>
                    <button type="button" onclick="clearScreen()" class="inputButton" value="C">C</button>
                    <button type="button" onclick="putToScreen(0); xValue += parseInt(0)" class="inputButton4 input" value="0">0</button>
                    <button type="button" class="inputButton4" onclick="compute()" value="=">=</button>
                    <button type="button" onclick="putToScreen('/')" class="inputButton4" value="/">/</button>
        </div>
    </div>
    <script type="text/javascript">
        var input = document.getElementsByClassName("inputButton");
        //var valueBox = document.getElementById("answer");
        var answer = document.getElementById("answer");

        // var xValue = do i +=
        var xValue = 0;
        var yValue = 0;
        var plusButton = 0;
        //var finalAnswer

        function putToScreen (x) {
            var node = document.createTextNode(x);
            answer.appendChild(node);
        }

        function clearScreen() {
            answer.innerHTML = "";
            xValue = 0;
            yValue = 0;
            plusButton = 0;
        }

        function add () {
            if (plusButton >= 1) {
                document.getElementsByClassName("input").onclick = "yValue +=";
            }
            var sum = parseInt(xValue) + parseInt(yValue);
            answer.innerHTML = sum;
        }

        //var sum = parseInt(xValue) + parseInt(yValue);

        function compute () {
            if(plusButton >= 1) {
                add();
            }
        }

`

Answer №1

Latest Update

After some feedback from @Ryan regarding my suggestion of using eval, I understand the concerns raised. While I still believe that eval can be used safely in certain controlled scenarios, it should always be approached with caution. For more insights on this debate, you can check out a related discussion on Stack Overflow.

However, a great alternative approach was suggested by @yckart, which leads me to make a new recommendation.

We can modify the compute function as follows:

function compute () {
  answer.innerHTML = new Function('return ' + answer.innerHTML)();
}

This way, we eliminate the need for complex calculation logic. Implementing a full-fledged recursive descent parser would indeed be quite challenging.

In response to your query about handling operations like square roots and squares: both eval and the Function method support any valid JavaScript expressions, including:

  1. Math.sqrt(number) for calculating square roots
  2. Math.pow(number, 2) for squaring a number

Code Snippet

function putToScreen (x) {
  var node = document.createTextNode(x);
  answer.appendChild(node);
}

function clearScreen() {
  answer.innerHTML = '';
}

function compute () {
  answer.innerHTML = new Function('return ' + answer.innerHTML)();
}
button {
  width: 2em;
}
<div id="answer"></div>
<hr>
<button onclick="putToScreen(this.innerText)" >1</button>
<button onclick="putToScreen(this.innerText)" >2</button>
<button onclick="putToScreen(this.innerText)" >3</button>
<button onclick="putToScreen(this.innerText)" >+</button><br>
<button onclick="putToScreen(this.innerText)" >4</button>
<button onclick="putToScreen(this.innerText)" >5</button>
<button onclick="putToScreen(this.innerText)" >6</button>
<button onclick="putToScreen(this.innerText)" >-</button><br>
<button onclick="putToScreen(this.innerText)" >7</button>
<button onclick="putToScreen(this.innerText)" >8</button>
<button onclick="putToScreen(this.innerText)" >9</button>
<button onclick="putToScreen(this.innerText)" >*</button><br>
<button onclick="clearScreen(this.innerText)" >C</button>
<button onclick="putToScreen(this.innerText)" >0</button>
<button onclick="compute()"                   >=</button>
<button onclick="putToScreen(this.innerText)" >/</button>

Answer №2

Each time a button is pressed, the xvalue and yvalue increase by the corresponding digit assigned to that button. For instance, if you enter 12, xvalue will first increase by 1 and then by 2.

Note

xValue+=n

Adding n to xvalue increases it by n. This can also be expressed as

xValue=xValue+ n

which may be more recognizable to some users.

Answer №3

It is important to treat user input as strings until specific operators are pressed (+, -, *, /). This means that digits should be added to the xValue variable as strings. For instance, pressing 1 would be represented as:

xValue += "1"

If the user then enters 12, the xValue becomes:

xValue = "12"

Once the user presses one of the specified operation buttons, it indicates that the number is complete and can be converted into a numeric value using parseInt().

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

How can a static website incorporate a local image without the need for backend functionality?

I have a unique challenge with my static website. It is designed to display a local image from the user's computer without utilizing a traditional backend system. The website itself is hosted on a static file server, and all image processing must be d ...

Obtaining a unique diamond pattern overlay on my Google Map

Currently, I am integrating Vue.js with vue-google-maps, and I have noticed a diamond-shaped watermark appearing on the map. After reaching out to Google support, they mentioned that this issue is specific to my tool, indicating it might be related to eith ...

Optimize my webpage for a specific location

While developing a game website, I am interested in learning how to enable only specific parts of my website to function while disabling the rest. How can this be achieved? ...

Looking for a way to store data in a sub-document in MongoDB? I am having an issue where my farm sub-documents

After many attempts, I am still facing issues while saving farm data for a User. I created an API to sign up a user and save their data, including the farm object. However, every time I try to update the code, the farm object turns into null. The goal is t ...

Is the ID Column in the Minimal Material Table Demo not appearing as expected?

Hey there, I'm in the process of developing a simple demonstration of a material table - Take note that this is a stackblitz link and for some reason, the id column isn't showing up. Here's a snippet from my app.component.ts: import { C ...

Styling Table Headers with JavaScript and CSS

Currently, I have a Javascript function that returns a specific value. When this value is returned, I want to dynamically change the colors of different table headers based on their id. Is there a way to change the color of a table header in javascript wi ...

How can I pass a value as an attribute from an Angular template to a directive?

Here's a directive I'm working with: <g-map-locations center={{myLocation}} zoom="4" id="map" class="map"></g-map-locations> The zoom parameter is used in Angular to set the zoom level for a Google Map: attrs.zoom = zoom setMapOpti ...

Webpage video stalling due to buffering

Currently, I am developing personalized video controls and have integrated a @progress event to monitor the video buffering progress and adjust the width of a progress bar div: <video @progress="videoBuffer($event)"> videoBuffer(e) { if ...

What is the process of generating a dynamic card/button element on an ASP.net webpage using information from the backend database?

I'm faced with a challenge of displaying employees' names and titles from a MSSQL Server database table on an ASP .NET webform as individual "card" objects. Currently, I am able to showcase a static number of records by using an asp button object ...

Adding a line break in a Buefy tooltip

I am trying to show a tooltip with multiple lines of text, but using \r\n or is not working. <b-tooltip label="Item 1 \r\n Item 2 \r\n Item 3" size="is-small" type="is-light" position="is-top" animated multilined> ...

Retrieve the duplicated items from an array by comparing two specific properties in JavaScript

I need assistance in identifying and retrieving duplicate objects within an array that share similarities in 2 specific properties. Consider the object structure below: let arry = [ {Level: "A-1", Status: "approved"}, {Level: &q ...

retrieving the webpage's HTML content from the specified URL using AngularJS

Utilizing the $http.get('url') method to fetch the content located at the specified 'url'. Below is the HTML code present in the 'url': <html> <head></head> <body> <pre style = "word-wrap: break ...

Other Components take turns submitting the form in one Component

Two components, CreateCandidate and Technologies are being used. CreateCandidate requires technologies from the Technologies Component. When passing the technologies to CreateCandidate, the form within CreateCandidate is submitted. Below is the code: Crea ...

Adonis 5 and Vue encountering the error message 'E_ROUTE_NOT_FOUND'

I am currently working on a project using Adonis v5 as the backend and Vue 2 as the frontend. I have encountered an issue where, after building the Vue frontend into the public Adonis folder, accessing a specific route directly in the browser results in an ...

Is it possible to swap a <div> element with the content of another HTML page using the .innerHTML method?

I am currently working on a project that involves loading different webpages into a <div> on my page once specific links are clicked. I came across a thread about using jQuery for this purpose, but I'm not familiar with it. Is there a way to ach ...

When the function is executed, the error message "obtaining ID

As I attempt to remove items from a group and automatically delete the group if there are no items left, I encounter an error in Vue indicating that 'id' is not defined. This seems puzzling to me because it should have already completed the opera ...

Find elements that are not contained within an element with a specific class

Imagine having this HTML snippet: <div class="test"> <div class="class1"> <input type="text" data-required="true"/> </div> <input type="text" data-required="true"/> </div> I'm looking to select ...

Implementing access restrictions for modules in NodeJS

In Node, is it possible to limit access or permit access only to specific modules from a particular module? Should I consider replacing the require function and object in the global scope for this purpose? I have concerns about the security of a certain mo ...

Tips on how to engage in a spontaneous audio experience

I am currently developing a Discord bot with the intention of having it play a random mp3 file upon joining a voice channel. case"join": message.delete( {timeout: 5000}) const voiceChannel = message.member.voice.channel ...

Issue with Bootstrap Navbar dropdown functionality not functioning correctly in browsers, but working fine on Codepen

I'm encountering an issue with a dropdown menu in the navbar of my document. The dropdown menu works fine in my codepen but not in my text editor (Sublime). I've tried various solutions and couldn't find a fix, so I'm reaching out here ...