What is the reason behind the undefined status of calc in the onclick event attribute?

Could someone kindly guide me on where I'm going wrong?

I am a budding developer and these concepts are fairly new to me. Can you offer your assistance?

Whenever I attempt to run my code, I encounter an error that reads "Uncaught ReferenceError: calc is not defined at HTMLButtonElement.onclick".

I aim to have the answer displayed within the div identified as "result" but unfortunately, it's not functioning as intended.

Here's the Markup:

<!DOCTYPE html>
<html>
    <head>
        <title>My First Calculator</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    </head>
    <body>
        <form>
            Value 1: <input type="text" id="value1">
            Value 2: <input type="text" id="value2">
            Operator: 
                <select id="operator">
                    <option value="add">Add</option>
                    <option value="sub">Subtract</option>
                    <option value="mul">Multiply</option>
                    <option value="div">Divide</option>
                </select>
                <button type="button" onclick="calc()">Calculate</button>
        </form>
        <div id="result"></div>
    </body>
</html>


enter code here

Javascript Code:

function calc() {
    var a = parseInt(document.querySelector("#value1").value);
    var b = parseInt(document.querySelector("#value2").value);
    var op = document.querySelector("#operator").value;
    var calculate;

    if (op == "add") {
        calculate = a + b;
    } else if (op == "sub") {
        calculate = a - b;
    } else if (op == "mul") {
        calculate = a * b;
    } else if (op == "div") {
        calculate = a / b;
    }
    document.getElementsByTagName("button")[0].addEventListener("click", calc);
}

Answer №1

I have tested this code in a CodePen demo that I set up: https://codepen.io/PavlosKaralis/pen/eYJRXMp?editors=1111

One important thing to note is that there is no need to include an event listener within the function; the onclick attribute serves as the event listener itself.

Additionally, it has been pointed out by another user that the script tag was missing:

<script src="./filename.js"> </script>

Answer №2

Your task involves attaching an event listener to an already "listened" event. A more efficient approach would be:

<script type="text/javascript">
    function performCalculation() {
        var num1 = parseInt(document.querySelector("#value1").value);
        var num2 = parseInt(document.querySelector("#value2").value);
        var operator = document.querySelector("#operator").value;
        var result;

        if (operator == "add") {
            result = num1 + num2;
        } else if (operator == "sub") {
            result = num1 - num2;
        } else if (operator == "mul") {
            result = num1 * num2;
        } else if (operator == "div") {
            result = num1 / num2;
        }
    }
</script>

Following this, you can update the end of the function to display the result in your HTML like so:

document.querySelector('#result').innerText = result;

I purposely omitted where to insert it, encouraging you to think and practice problem-solving skills essential for becoming a proficient developer ;)

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

Reveal Vue component functionality to external projects

Currently, I am researching ways to share my Vue component with other projects without the need to publish it on NPM. I came across a helpful resource that explains how to publish a Vue component on NPM: how-to-publish-your-vue-js-component-on-npm-62b67df ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Stop the browser from automatically loading a file that is dragged and dropped into it

I've implemented an HTML5 drag and drop uploader on my webpage. It functions perfectly when a file is dropped into the designated upload area. Unfortunately, if I mistakenly drop the file outside of that area, the browser treats it as a new page loa ...

Add up the numbers in a single column

I have an array of values: array = [ { "id": 1, "Price": 100, "Item": {"id": 1, Name: "A"}, "Date": {"id": 1, ...

Checking the time using jQuery

Looking for some guidance on using jQuery to validate a Time field. My goal is to restrict users from entering times before 18:00. I know HTML5 field validation can achieve this, but I find jQuery offers more flexibility in formatting user responses. Plus ...

A step-by-step guide on harnessing the power of RPG.J

Attempting to utilize the RPG.js library as it appears to be quite powerful. I checked out the official tutorial but am struggling to understand certain aspects, particularly State 4: "Initialize the canvas in your JS file." Any guidance on which one to ...

The function react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext is not recognized when implementing Autocomplete within Material UI

Every time I attempt to create an Autocomplete tag utilizing Material UI, an error pops up, which can be seen in the following link: https://i.sstatic.net/kxKR4.png The Autocomplete code snippet is as follows: import React, {useState, useEffect, useCo ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

Merge web address when form is sent

I'm currently working on a search application using the Django framework and the Yelp API as my backend, which is functioning properly. However, I am facing some challenges with the frontend development, specifically integrating Leaflet.js. My search ...

Interacting with shadow DOM elements using Selenium's JavaScriptExecutor in Polymer applications

Having trouble accessing the 'shop now' button in the Men's Outerwear section of the website with the given code on Chrome Browser (V51)'s JavaScript console: document.querySelector('shop-app').shadowRoot.querySelector ...

Using jQuery, you can pass variables to a function in JavaScript

Seeking advice on the most effective method for implementing this functionality. I have a table that displays information, with a button labeled "Edit/View" in the last column. When the user clicks on the button, a div section appears with additional edita ...

Bootstrap's media object is a powerful feature that allows for the

I am currently learning BootStrap and running into some challenges with media objects. My goal is to design a basic container with an image on the left side and text on the right side. However, I am facing an issue where when my content exceeds one line, ...

Experiencing difficulty in personalizing VueDatePicker

<template> <VueDatePicker v-model="date" ref="datepicker" /> </template> <script setup> import { ref } from 'vue'; const date = ref(); const datepicker = ref(null); const yourCustomMethod = () =&g ...

Detecting a click on the background div in Angular without capturing clicks on child divs

Over at ollynural.github.io, I've been working on creating a pop-up div in the portfolio page that provides additional information about the project you select. To close the pop-up, I have implemented an ng-click feature so that clicking on the main p ...

Step-by-step guide to building multiple layouts in React.js using react-router-dom

For my new web application, I am looking to create two distinct layouts based on the user type. If the user is an admin, they should see the dashboard layout, while employees should be directed to the form layout. Initially, only the login page will be dis ...

Rendering to a texture using the pingpong method in Three.js went smoothly, with no issues detected and the output was not

I attempted to implement the pingpong texture swap technique to generate smoke in threejs by following a tutorial that was published some years ago. Unfortunately, this tutorial utilizes an outdated version of threejs, and I am experiencing difficulties tr ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

Is there a way to use JavaScript to modify the position of a div element

Can we adjust the div position using CSS (absolute or relative) with JavaScript? Here's an example code snippet: <div id="podpis" style="margin-top: 2rem;"> <div class="invoice-signature"> <span><?=$xml->sanitiz ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

What steps can be taken to ensure web resources such as scripts, images, etc are loaded from the correct location when implementing CORS support in a web application

In my local IIS, I have two asp.net mvc applications running on different ports. One is "App1" on port 1066 and the other is "App2" on port 1067. My requirement is for App2 to post data to an endpoint in App1 for validation. If the data is valid, App1 sho ...