The calculator is experiencing issues with JavaScript functionality

Having some trouble developing a calculator using HTML5, CSS, and JavaScript. After passing my HTML and CSS through validators successfully, I encountered issues when adding JavaScript functions to enable the functionality of the buttons on the calculator. Unfortunately, nothing is showing up on the screen and none of the functions are executing. What could be the error in my code? Any assistance would be greatly appreciated.

Thank you.

Below is the snippet of my HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- Linking the .css file -->
    <script type="text/javascript" src="calculator.js"></script>
    <link rel="stylesheet" href="calculator.css">
    <title>Calculator Front-End</title>

</head>

<body>
        <form>

            <input type="text" id="screenid" class="screen" name="calcscreen" value="0">

            <p>
                &nbsp;
            </p>


            <table>
                <tr>
                    <td>&nbsp;</td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">7</button></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">8</button></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">9</button></td>
                    <td><button id="add" class="symbolbutton" onclick="addDisp(this)">+</button></td>
                </tr>

                <tr>
                    <td></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">4</button></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">5</button></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">6</button></td>  
                    <td><button id="sub" class="symbolbutton" onclick="addDisp(this)">−</button></td>
                </tr>

                <tr>
                    <td></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">1</button></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">2</button></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">3</button></td>
                    <td><button id="prod" class="symbolbutton" onclick="addDisp(this)">×</button></td>
                </tr>

                <tr>
                    <td></td>
                    <td></td>
                    <td><button class="digitbutton" id="digit" onclick="addDisp(this)">0</button></td>
                    <td><button id="result" class="symbolbutton" onclick="doCalc(this)">=</button></td>
                    <td><button id="div" class="symbolbutton" onclick="addDisp(this)">÷</button></td>
                </tr>

            </table>
        </form> 
</body>
</html>

-------------------------------------------------------------------------
-------------------------------------------------------------------------

****

Please find below my calculator.js content:
****

//Variables and constants used for functions

var previousvalue = 0; //Last button pressed
var newvalue = 0; //Current button being pressed
var previousop = 'plus';
var previnputcn = 'symbolbutton' //Classname of the previous button

//Function to display elements on screen

function addDisp(button) 

    {

        if (button.className == "digitbutton") 
            {
                if (previnputcn == "symbolbutton") 
                {
                    newvalue = document.getElementById("digit").value;
                }

                else 
                {
                    newvalue = newvalue + document.getElementById("digit").value; 
                }
            }

        document.getElementById("screenid").value = document.getElementById("screenid").value + newvalue; 

        if (button.className == "symbolbutton") 
            {
                var calcResult = doCalc(previousvalue, newvalue, previousop);

                if (calcResult <= 1000000 || calcResult == "ERROR") 
                {
                    newvalue = calcResult;
                }

                document.getElementById("screenid").value = document.getElementById("screenid").value + newvalue;

                if (newvalue == "ERROR")
                    {
                        previousvalue = 0; 
                    }

                else 
                    {
                        previousvalue = newvalue; 
                    }

                previousop = button.id; 

            }
        previnputcn = button.className; 

    }


/*Function that handles all calculations*/

function doCalc(newvalue, previousvalue, previousop)
    {
        var output = newvalue;

        if (previousop == "plus")
            {
                output = parseInt(previousValue) + parseInt(newvalue);
            }
        else if (previousop == "minus") 
            {
                output = parseInt(previousValue) - parseInt(newvalue);
            }
        else if (previousop == "times")
            {
                output = parseInt(previousValue) * parseInt(newvalue);
            }
        else if (previousop == "divide")
            {
                if (newvalue != 0)
                    {
                        output = parseInt(previousValue) / parseInt(newvalue);
                        output = parseInt(output);
                    }   
                else 
                    {
                        output = "ERROR";
                    }
            }
        calcResult = output;
    }

Answer №1

Your code has a couple of issues that need to be addressed.

  1. Ensure to specify the type of each button as type="button". By default, the type for buttons is "submit", leading to the form being submitted every time a button is clicked and causing the page to refresh repeatedly.
  2. It's important to note that most of your buttons share the same id. The id attribute should always be unique for each element.

Despite these challenges, you are passing the button element as an argument to the addDisp function on click. Utilize this opportunity to retrieve the value more effectively.

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

Having trouble getting the Bootstrap tooltip to work on a Select option?

Is there a way to have a tooltip displayed for each option in the select box? <select ng-model="rightList" class="form-control" size="13" multiple> <option ng-repeat="item in selectedList" value="{{$ ...

The issue with the autoresize feature in the tinymce plugin arises when trying to delete HTML img content using the backspace

When using the tinymce editor with the autoresize plugin enabled, I have noticed that it works correctly with text. However, there is an issue when inserting HTML content via execCommand. For example, if I insert the following code: <div> < ...

Exploring the concept of promises in node.js for recursive functions

I'm attempting to use recursive calls in order to fetch data from redis, halting and returning when the members return null. My data is inserted as shown below: SADD parents.<name> <parent1> <parent2> SADD parents.<parent1> & ...

VueJS emits a warning when filtering an array inside a for loop

I'm encountering an issue with my filtering function in VueJS. While it works fine, I am seeing a warning message in the console. You can check out this example to see the problem. The problem arises when I need to filter relational data from a separ ...

Retrieve from MongoDB the items where the age is greater than 10 using the find function in the learngyoumongo

Currently working my way through the learnyoumongo tutorial and facing a challenge in part 3. The task involves a test database filled with parrots, and the objective is to retrieve the parrots whose age exceeds a specified input value. Despite using Mongo ...

Retrieve the value of an input text within a table data cell using JavaScript

I have set up a table using CGridView, which includes input text fields for user input. The problem I'm facing is that I can retrieve the text from table cells without input fields, but not from those containing input fields. PHP: <?php $this-> ...

Problem encountered when trying to use a single button for both opening and closing functionality in JQuery

Hello everyone, I'm currently working on creating a button that toggles between opening and closing. When clicked the first time, it should open, and when clicked the second time, it should close and reset. Here is the code I've written so far. ...

CSS - using numbers to create dynamic background images

I am looking to create a design where the background images in CSS display increasing numbers per article, like this example: This idea is similar to another post on Stack Overflow discussing using text as background images for CSS. You can find it here: ...

Optimizing CSS for printing by eliminating unnecessary white space with media queries

Appreciate your assistance! I'm currently working on a solution to print a specific div using CSS Media queries. When the user clicks on print, I want to hide all other elements except for the body div they chose. However, I'm facing an issue whe ...

The "Splash Screen Div" page displayed during transitions and page loading

Creating a "Splash Screen Div" for a loading page involves waiting until everything is loaded and then hiding or moving the div off screen. Below is an example: index.html <div id="loading-Div"> <div id="bear-Logo"> < ...

Can a plugin be executed as a test?

I am currently using HTMLhint, however, I would like to have it run as a test rather than just through the command line plugin. Is there a way to achieve this and if so, how can I do it? I have searched online but haven't been able to find a solution ...

"Transferring an array of data to a Laravel controller via AJAX: A step-by-step guide

Is there a way to send arrays of data to the back-end all at once? The Problem 1. This is what I'm currently sending: array:5 [ "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj" "product_id" => "21" "specification_id" => "6" " ...

Using JQuery to reverse the action of hiding an image

Having some trouble with my Javascript and JQuery skills, so bear with me. I've set up a gallery of images where users can drag and drop them into a designated drop zone. Everything works fine when dragging an image from the gallery to the drop zone a ...

Unexpected arrows are being added to the dropdown menus in a responsive Twitter Bootstrap menu

I am puzzled by the behavior of my responsive twitter bootstrap nav. Take a look at this screenshot: The issue is with the strange up-pointing arrows that appear. The carets are fine, but these extra arrows are not desired. They disappear if I remove all ...

What is the reason behind the Chrome icon flickering momentarily while loading certain web pages?

I recently put together a basic html document, here it is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <title>Just a test.</title> </head> <body> <svg ...

What is the best way to combine two arrays into a single array using AngularJS?

Here is a code snippet: $scope.studentDetails=[]; $scope.studentDetails=[0][id:101,name:one] [1][id:102,name:two] [2][id:103,name:three] $scope.studentMarks=[]; $scope.studentMarks=[0][id:101,marks:78] ...

Updating a specific row in a table using PHP and SQL

I am having an issue with updating rows in a table that pulls information from a database. Each row has an input tag labeled COMPLETE, which the user can click on to update the database by changing a boolean field from 0 to 1. However, I am facing a prob ...

Is there a resource available that can help me create a jquery/ajax image slider/carousel similar to this?

One thing that really caught my eye is how cnn.com has implemented this feature. I think it would be a great addition to the website I'm currently working on. I particularly like the page numbering, as well as the first, previous, next, and last butto ...

Filter and transfer data from one Angular array to another

As a newcomer to Angular, I am working with an array of events containing multiple arguments. My goal is to filter these events and separate them into two new arrays: upcoming events and past events. Below is a snippet of the TypeScript code I am using: a ...

grab the destination URL from the embedded frame

Thank you for your attention. I am working with three iframes spread across different HTML documents. Here is how they are organized: In the file iframemain.html, there is: <iframe src="iframeparent.html" width="100%" height="600"> </iframe> ...