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

Tips to detect a specific animation completion on an element?

How can I ensure that a specific animation ends when multiple animations are triggered on an element? My scenario involves an overlay song list that appears when a list icon is clicked. The challenge lies in closing the menu smoothly. I have implemented a ...

What is the best way to eliminate a duplicate item from the shopping cart without actually deleting it?

I developed an e-commerce platform with a cart feature using the context API. However, I encountered an issue where removing one item from the cart also deletes another item if there are two of the same items in the cart. How can this be prevented? Below ...

The Selenium Webdriver's isSelected() method in Chrome browser does not return true for radio buttons

I have been attempting to confirm whether my radio button is selected or not, but I keep receiving a false value even after selecting the radio button. Here is the HTML code: <div class="controls tss-radio-text-format"> <label class= ...

challenge encountered while trying to remove ScrollTop feature on mobile gadgets

Currently facing a challenge with responsive design - I have implemented a sticky navbar effect that works seamlessly on desktop, but causes usability issues on mobile. When scrolling down on the mobile version, the sticky navbar obscures the text on the s ...

Leveraging the power of PHP and AJAX for seamless transmission and reception of JSON data through a

I am in the process of creating a basic form that consists of a single text field and a submit button. The goal is to have the entered value posted to a $.getJSON method upon clicking the button, which will then retrieve a JSON response and display it on t ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Vue: setInterval not updating timer variable

Here is my code for updating and displaying the number of elapsed seconds: <template> <div> {{timerValue}} </div> </template> <script> export default { name: "App", components: { }, da ...

Adjust div height to match the dynamic height of an image using jQuery

I'm facing an issue with my image setup. It has a width set to 100% and a min-width of 1024px, but I can't seem to get the 'shadow' div to stay on top of it as the window size changes. The height of the shadow div also needs to match th ...

How to transfer data from JavaScript to PHP using AJAX

After spending countless hours attempting to make this function properly, I have come to you for assistance :) I have created a PHP page that can exhibit files from a server. I am able to modify the files using an editor plugin, where the Textarea tag is ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

Sorry, but we're unable to provide a unique rewrite of text that is an original error message

Trying to fetch data from a MySQL database using Next.js API routes, I encountered the following error: Error: No response returned from the route handler Below is an example of the code being used: import { NextResponse } from "next/server"; impor ...

Personalize Dropdown Menu, determining when to initiate the hide menu action

When creating a dropdown using ul and li tags, I am faced with the dilemma of determining the ideal time to hide the dropdown menu. The dropdown menu is designed to display values based on user input as they type, updating dynamically. Initially, I had se ...

Changing the route variable in React Native's bottom bar tab functionality

I am looking to create a consistent bottom tab bar that remains the same on every screen, but I want the routes of the tabs at the bottom to change dynamically. For example, in Screen1, the tab at the bottom should route to 'Screen2'. Then, when ...

The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and ...

Anti-virus programs are preventing long-standing AJAX connections

Hey there, I have come across something quite strange while developing a web application that relies on long-held HTTP connections using COMET to stream data between the server and the application. The issue I've encountered is that some anti-virus p ...

Creating a Tree Checkbox using jQuery without relying on pre-made plugins

The data structure provided appears to be hierarchical, but I am unsure if it follows the Adjacency list or Nested List model. Regardless, it is relatively simple to gather this hierarchical data. For instance, to retrieve the entire tree, you can use: SE ...

Run an npm script located in a different package

Imagine I have two node packages, one named parent and the other named child. The child package contains a package.json file with some scripts. Is it viable to merge the scripts from child into the context of parent? For instance: child/package.json: "s ...

Having trouble accurately obtaining the height of a DIV element using jQuery

After trying to troubleshoot on my own, I ran into a roadblock due to my specific requirements not being met by existing solutions. The issue at hand is as follows: I have a sticky DIV element positioned to the left, nested within another DIV Element wit ...

utilizing the setState function to insert an object into a deeply nested array

Currently, I am utilizing iReact setState to attempt posting data to my object which consists of nested arrays. Below is how my initial state looks: const [data, setData] = useState({ working_hours: [ { id: '', descrip ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...