Listening to events for this situation

As a beginner in JavaScript, I have been studying event listeners and how to apply them to my code. I am currently working on a basic calculator project where users input two amounts into HTML fields for addition. Although my current code functions correctly, it does not update the total amount when the field values change. This is why I believe I need an event listener. Can you guide me on how to implement this in my scenario? I have reviewed online examples but still struggle with the concept.

Should I incorporate some of my code within a function?

Note: It's important that my global variable "paytotal" always displays the most up-to-date results so I can access this data across my page.

Below is my existing JavaScript:

var payamount1 = document.getElementById("amount1").value;
var payamount2 = document.getElementById("amount2").value;
var paytotal = Number(payamount1) + Number(payamount2);
document.getElementById("payment-due").innerHTML = paytotal;

This is what my HTML looks like:

<input type="text" id="amount1" placeholder="enter amount 1">
<input type="text" id="amount2" placeholder="enter amount 2">

<div class="details-row">Total payable: <span id="payment-due"></span></div>

Answer №1

Event listeners are designed to detect when a specific action occurs. In this scenario, the ideal event to listen for is 'input' as it captures all necessary changes.

To simplify the process, assigning a class to your inputs would be beneficial.

The following JavaScript code will apply an input listener to the assigned input elements:

var amounts = document.querySelectorAll(".amounts");
var paytotal = 0;
amounts.forEach(function(el){
  el.addEventListener("input",function(){
   var payamount1 = document.getElementById("amount1").value;
   var payamount2 = document.getElementById("amount2").value;
    paytotal = Number(payamount1) + Number(payamount2);
   document.getElementById("payment-due").innerHTML = paytotal;
});
});
<input class="amounts" type="text" id="amount1" placeholder="enter amount 1">
<input class="amounts" type="text" id="amount2" placeholder="enter amount 2">

<div id="payment-due"></div>

Answer №2

To enhance functionality, add an event listener to each input field triggering a function (calc) that contains your custom code.

var amount1 = document.getElementById("amount1");
var amount2 = document.getElementById("amount2")
amount1.addEventListener('change', calc);
amount2.addEventListener('change', calc);

function calc() {
    var payamount1 = amount1.value;
    var payamount2 = amount2.value;
    var paytotal = Number(payamount1) + Number(payamount2);
    
    document.getElementById("payment-due").innerHTML = paytotal;
}
<input type="text" id="amount1" placeholder="enter amount 1">
<input type="text" id="amount2" placeholder="enter amount 2">
<div class="details-row">Total payable: <span id="payment-due"></span></div>

Answer №3

There are numerous ways to achieve this task. Here is one method; Ensure to validate that the result is not NaN

function calculateTotal() {


  var inputValue1 = document.getElementById("value1").value;
  var inputValue2 = document.getElementById("value2").value;

  if (inputValue1 != '' && inputValue2 != '') {
    var totalValue = Number(inputValue1) + Number(inputValue2);
    
    if(!Number.isNaN(totalValue))document.getElementById("result-display").innerHTML = totalValue;
  }

}
<input type="text" id="value1" placeholder="enter value 1" onchange="calculateTotal()">
<input type="text" id="value2" placeholder="enter value 2" onchange="calculateTotal()">
<div class="details-area">Total amount: <span id="result-display"></span></div>

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

Creating a sleek animated analog clock using CSS and jQuery

I am facing a small issue with my CSS3/jQuery analog clock. Currently, the movement of the clock hands is a bit abrupt. I would like the animation to be smooth. I attempted using transition: all .1s, but it gets messy when the clock hands reach the top po ...

What is the method for modifying the background color of the inner circle in a highchart doughnut chart?

Trying to Modify the Background Color of a Highchart Doughnut Desired Outcome https://i.sstatic.net/Fk9oS.png Current Outcome https://i.sstatic.net/CTZqZ.png JS Fiddle Link : https://jsfiddle.net/shantanugade/f5ojh13z/1/ Seeking assistance with this is ...

Combining and overriding two JavaScript objects in real time

I possess two objects. userprofile = { id: 1, email: hello@gmail.com, user: { id: 1, username: test, } } userprofile2 = { email: bye@gmail.com, user: { username: testtest, } } My goal is to merge userprofile with userprofile2, e ...

Exploring the wonders of math in Angular with ng-repeat

Exploring the realm of mathematics within an angular expression, let's consider a scenario where a user can either have credit on the site or receive a percentage discount. Below is the code snippet in question: <div ng-repeat="item in NewArrivals ...

Initiate a series of tasks and await their completion using RxJS / Redux Observables

My app requires an initialisation action to be fired, followed by a series of other actions before triggering another action. I found a similar question on Stack Overflow However, when attempting this approach, only the initial APP_INIT action is executed ...

The AngularJs project is currently experiencing issues when trying to function as a single page web application

I'm currently working on incorporating AngularJS into an existing web project that uses jQuery. Here is a snippet of my code: <div class="medya" ng-repeat="d in data" masonry-item-dir> <a href="{{d.Url}}" class="onizleme"><img src="{ ...

Retrieve data from FileReader's onload event asynchronously in Javascript

Although this question has been asked numerous times before, I have reviewed the answers provided and still cannot get my code to work. I am working with Angular 2. I have input tags for file insertion. The file successfully reaches the component, but when ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

Having trouble with Selenium WebDriverJS on both FireFox and Internet Explorer

Having developed multiple JavaScript tests using chromedriver to run them in Chrome, I am now facing the challenge of running these same tests in FireFox and IE. The test below is functional in Chrome: var assert = require('assert'), test = requ ...

How to automatically generate a serial number using JavaScript each time a click event occurs

continuous problem with repeated serial numbers Serial number remains the same after each click $(document).on('click', '.menu-item', function() { var menu_id = $(this).attr('id'); var _token = $('input[name="_ ...

Describe a Typescript Interface Value as a collection of strings or any input provided as an argument

Uncertain if the question title is accurate - currently developing react components within a library that has specific predefined values for certain properties. However, additional values may need to be added on a per usage basis. So far, this setup is fun ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

What is the procedure for verifying the type of an element using chai?

Is there a way to determine if an element is either an "a" tag or a "div" tag? I've tried the following code, but it's not working as expected: it('has no link if required', () => { const wrapper = shallow(<AssetOverlay a ...

What is the way to utilize a scope variable within an ng-repeat filter?

I'm feeling a bit lost trying to navigate through this task with AngularJS. As a newbie to the framework, I'm struggling to find out how to achieve what I need. I have a group of users that I am looping through by using ng-repeat, but I can' ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...

"Create a function that allows for the dynamic addition of elements to a

I want to dynamically add more li elements, similar to the first one, by simply clicking a button. Unfortunately, the example provided on jsfiddle is not functioning as intended. document.onload = init; function init(){ document.getElementById('a ...

Leveraging the useRef hook to adjust the CSS styling of a React component

Currently, I am working on changing the style of a react component by utilizing the useRef hook. So far, I have implemented the useRef hook to reference the specific component whose style I want to modify when clicking on two buttons. Despite my efforts, I ...

JavaScript and CSS Modal showing incorrect data

Currently, I am utilizing a Jinja2 Template within Flask to render an HTML document. The process involves passing a dictionary called "healthy_alerts" into the Jinja template. Below is a snippet of the dictionary (with sensitive values altered): healthy_a ...

Updating the state on a click event triggered by a MenuItem in React using Material UI

I'm currently working on implementing state changes based on dropdown selections using Material UI. However, I've encountered an issue where the code snippet below (simplified) only returns the list item, and I'm unsure what steps to take n ...

What is the proper way to connect an external Javascript file to an html document within a Play Framework project?

Below is the content of my scala.html file: @() <!DOCTYPE html> <html> <head> <title> Spin To Win </title> <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/styles.css")" ...