Output discrepancy detected in input tag functionality

I'm trying to create a function where, upon button click, the sum of values in two input texts is displayed, but no matter what values I enter, it always outputs 0. What am I missing? Since both inputs default to 0, their sum is also showing up as 0. HTML

<!DOCTYPE html>
<html>
<head>
    <title>WeB </title>
</head>
<body>
    <input type="number" id = "num1" >
    <input type="number" id = "num2" >
    <button id = "add">+</button>
    <script src = "app.js"></script>
</body>
</html>

JS

let num1 = Number(document.getElementById('num1').value)
let num2 = Number(document.getElementById('num2').value)

document.getElementById("add").addEventListener("click",function(){
    console.log(num1,num2);
    console.log(num1+num2);

})

Answer №1

Make sure to update the input value by clicking the button

document.getElementById("add").addEventListener("click", function() {

  let num1 = Number(document.getElementById('num1').value)
  let num2 = Number(document.getElementById('num2').value)


  console.log(num1, num2);
  console.log(num1 + num2);

})
<input type="number" id="num1">
<input type="number" id="num2">
<button id="add">+</button>

Answer №2

The sequence of events unfolds as follows:

  1. Start by reading the input values (which are initially empty strings), converting them to numbers (resulting in 0), and then storing these values in variables.
  2. Attach an event listener that will add these numbers together upon clicking something.
  3. Proceed to enter text into the inputs.
  4. Upon clicking the button, the following actions occur:
    1. The current values of the variables get logged.
    2. The values of the variables are summed up.

The original data remains intact within the variables, reflecting the values from when the input was initially read.

In order for the process to work correctly, it is necessary to integrate step 1 into step 4 (specifically within the function employed as the event listener).

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

Storing text data from Quilljs in Laravel 8 database

I am facing an issue with saving Quilljs Editor content to my database. Whenever I try to save it, nothing gets saved. Is there a method to successfully save Quilljs content to the database and also retrieve the data from the database to populate the Quill ...

Center Checkboxes in Bootstrap 4 Form Input

I am working with a Bootstrap Form that contains checkboxes. One specific scenario involves a large number of options to choose from. Currently, these options are displayed in a single long list, which can make it difficult for users to read and select the ...

An issue arises when I attempt to import framer-motion

Upon importing framer-motion in the following manner: import { motion } from "framer-motion"; An error is triggered: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefi ...

Mapping FuelPHP routes to Angular routes

Currently, my application has routes and request handling mechanism implemented in FuelPHP for calculating templates on the server side. From what I have observed, processing templates on the server side tends to be slower. Therefore, I am interested in t ...

Can we enhance this JavaScript setup while still embracing the KISS principle (Keep it simple, Stupid)?

I have completed the following tasks: Ensured all event handlers are placed inside jQuery DOM ready to ensure that all events will only run Defined a var selector at the top of events for caching purposes Please refer to the comments below for what I be ...

Could this potentially be a good fit for a JavaScript Closure implementation?

This code is functional, but I've been contemplating whether it could benefit from implementing closure. Let me explain. What I aim to achieve is: $(".trigger").click(function() { $(this).parents(".heading").next(".list").slideToggle("slow", ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

What are the steps to adjust image size using CSS in an email signature?

Having trouble with my email signature. It appears fine on my end, but when the recipient replies, the images are oversized and the css is not rendering correctly in their response. I'm puzzled as to why this is happening. Here's the code snippe ...

What are the steps to ensure Submit() functions properly?

Two links on a jsp page share a common javascript function func1 as the handler for their onclick events. func1 submits a form that contains both links, resulting in a redirect to a servlet. func1 is defined as: function func1(someValue, form) { getEle ...

Double firing of beforeUpdate event observed in Vue for recursive components

Recently delving into the world of vue js, I've been tinkering around with a recursive tree example inspired by the official example found here. While the original example starts with treedata containing a single root and multiple children, my goal w ...

Troubleshooting problem with Angular Materials' md-datepicker not displaying correctly in wide browser windows

While using the md-datepicker component in my application, I noticed that it does not display properly on larger browser widths. It only seems to work as expected on small and x-small viewports. Please refer to the attached screenshot for reference. This ...

Tips for integrating tooltips in a dynamic highcharts chart

This image shows the desired final output View Highcharts here and I am looking to merge the date and stock value in a single tooltip, how can this be achieved? highcharts ...

Implementing a feature to store highscores in a database using AJAX

I have developed a canvas game that is integrated with a website. I am looking to implement a feature where the player's highscore is posted to a database that I have created. The relevant portion of my game script responsible for updating the highsco ...

Transferring reference from a parent component to a child component

One of my components is called ChatScroller, which manages scrolling in a chat by autoscrolling when new messages come in. Here's a simplified version of it: class ChatScroller extends Component { scrollRef = node => this.scrollNode = node c ...

Disable Stripe with a testing credit card number

I successfully implemented a basic checkout system with Stripe and tested it using the following test credit card number: 424242424242 However, I now need to switch to development mode and prevent Stripe from recognizing all test credit card numbers as v ...

Alteration of icon size in input field using jQuery unintentionally

My issue involves an input field where users can input text from an array of emojis. When a user selects an emoji, it should display as an icon styled by an external stylesheet. However, there are two problems: The name of the icon appears on top of the ...

An advanced view engine capable of handling both ajax requests and direct function calls

In Node.js (Express), I am seeking a method to present a template in two different ways: one normally as HTML and the other as JSON, specifically for Ajax requests. Assume I have a swig template structured like this: {% extends 'layout.html' %} ...

Broken styles when using Material UI with babel and the 'with styles' feature

We've implemented babel and lerna to maintain specific elements of our react web app separately. While the setup has been effective thus far, we're encountering styling issues when generating the static build. The main project is not processed t ...

Text positioned on the right side of the image, appearing to hover above

After finding a helpful example on Stack Overflow, I successfully implemented a similar layout for product boxes in a JSFiddle. I then replicated the CSS and HTML almost exactly on my Wordpress blog, but encountered an issue where the title, description, a ...

Learn how to easily filter multiple queries within a table using W3.JS, where each query is delimited by a semicolon (;)

Everything in the code I've typed seems fine, but I'm curious about how to separate each word I search for with a ;. This is the code I have: <!DOCTYPE html> <html> <title>W3.JS</title> <meta charset="utf-8"> <l ...