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

Create dynamic automatic titles in HTML with JavaScript

Below is the code snippet to add an image with a link to the home-page and an h1 with the document name (if there isn't one already). This HTML code includes a JavaScript file reference in the <head> section and uses a <h1> tag for the ti ...

How come certain rectangles vanish when one rectangle completely fills the space?

Currently, I am encountering an issue with CSS paint worklet and I am trying to determine if it's a browser bug or an error on my end. In the worklet, I am drawing multiple rectangles. Strangely, when one rectangle covers the entire area, the others s ...

Learn the process of uploading a file using FormData alongside multer in node js. Experience the issue of receiving undefined in req.file and { } in req.body

Is there a way to successfully upload a file using FormData along with multer in Node.js? I seem to be encountering issues as req.file shows undefined and req.body displays {}. Check out the HTML code snippet below: <input type="file" name=&q ...

Troubleshooting Issues with Form Inputs in JS/Angular Using Places API and document.getElementById Method

I have integrated the Google Places API to automatically populate locations/destinations into a form after a user searches. The auto-population works correctly, but I am facing an issue when trying to submit the form into my database – the object is alwa ...

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

Method in Vue.js is returning an `{isTrusted: true}` instead of the expected object

I am having an issue with my Vue.js component code. When I try to access the data outside of the 'createNewTask' function, it renders correctly as expected. However, when I attempt to log the data inside the function, it only returns {isTrusted: ...

Can you explain the distinctions among <Div>, <StyledDiv>, and <Box sx={...}> within the MUI framework?

When exploring the MUI documentation, I came across a table of benchmark cases that can be found here. However, the differences between the various cases are not clear to me. Can someone please explain these variances with real examples for the following: ...

Is the ng-style not displaying the background image with the interpolated value?

I have been attempting to update the background image of a div using angular ng-style. Below is the code I am working with: <div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div> However, ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

Exploring the intricacies of Knockout JS mapping nested models using fromJS function

I am struggling with understanding how to effectively utilize the Knockout JS Mapping Plugin. My scenario involves nested models, and currently I am only using the ko.mapping.fromJS() in the parent model. However, I have noticed that the computed values ar ...

Having trouble with the express message! I can't seem to access the template I created

I am looking to receive a notification similar to an alert, as described in this link: https://github.com/visionmedia/express-messages By default, I receive something like this https://i.stack.imgur.com/9XlA9.png If I use a template, I do not get any out ...

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

What steps should I take to make sure that the types of React props are accurately assigned?

Dealing with large datasets in a component can be challenging, but I have found a solution by creating a Proxy wrapper around arrays for repeated operations such as sorting. I am looking to ensure that when the data prop is passed into my component as an ...

"How to dynamically fill a text input field from a table using jQuery when a specific value is selected, potentially involving multiple rows (possibly

Scenario I created a form that allows users to place orders for articles. These articles are displayed in a table within another form, where each article is listed with its code, description, and price. The goal is for users to select an article from th ...

What is the best way to apply absolute positioning to an image tag that is related to

I'm completely new to both rails and javascript. In my app, I have a table of venues categorized by type and area. These venues are displayed as partials on the index page, each with its own icon that appears on a map located to the left of the screen ...

Tips for creating fonts that adjust depending on the length of characters

Is there a way to adjust the font size of a paragraph based on the space available in its containing div, depending on the length of characters? For instance: p{ font-size:15px; } <div class="caption"> <p>Lorem ipsum dolor sit amet, consect ...

Is it possible to remove the address bar from appearing on a browser when a page loads?

I am in the process of developing a customer wifi landing page, and although we have made progress with ensuring it is the first page that loads, I want to take it a step further. My goal is to require customers to agree to our usage policy before gaining ...

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...

Is it possible to customize the selected color of the Chip component?

Is there a way to change the clicked color of a Chip component without modifying the theme.js file? I attempted to override the classes with the desired colors, but it still defaults to primary/secondary colors. This information was found in the source co ...