How can JavaScript automatically calculate the sum of various numbers entered into multiple input fields?

I would like to automatically add different numbers entered in multiple input fields using JavaScript.

Is there a way to calculate the sum of numbers entered in various input fields using JavaScript?

"The input field consists of n numbers..." and I am utilizing the clone function for these input fields.

https://i.sstatic.net/2XRrg.png

I am only concerned with numerical values in the input fields, not text fields. You can refer to a similar model here. Please note that the names and IDs here are different from the example provided.

Can anyone guide me on how to achieve this? Your help is greatly appreciated.

Answer №1

You can implement an onchange event on all input fields that need to be summed up

<input class="sum" onchange="add()" />

This script will calculate the sum and display it in the total input field:

function add(){
 total = 0;
 sum = document.getElementsByClassName("sum");
 for(a = 0; a < sum.length; a++)
   {
     console.log(sum[a].value);
     total += parseInt(sum[a].value || 0);
  }
  document.getElementById("total").value = total;
}

Demo:

function add(){
 total = 0;
 sum = document.getElementsByClassName("sum");
 for(a = 0; a < sum.length; a++)
   {
     console.log(sum[a].value);
     total += parseInt(sum[a].value || 0);
  }
  document.getElementById("total").value = total;
}
One   <input class="sum" onchange="add()" /><br/>
Two  <input class="sum" onchange="add()" /><br/>
Three <input class="sum" onchange="add()" /><br/>
Four  <input class="sum" onchange="add()" /><br/>
Total   <input id="total"  /><br/>

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

"Exploring the integration of video.js with React Hooks: A step-by-step

I have been utilizing video.js within the React framework and am now looking to transition to React Hooks. The current version of my React project is 16.8.3 Below is the initial functioning code: import React, { PureComponent } from 'react'; i ...

Loading a unique shape using JSON within the KineticJS framework

Is there a way to load a unique custom shape using a Json file in Kinetic JS? The documentation I found only covers loading normal shapes. ...

Show the current temperature data retrieved from the weather API

I'm trying to figure out what's causing the issue with the temperature not displaying. Can anyone help me identify and fix the error? <script type="text/javascript"> $.ajax({ url: 'https://api.weather.gov/gridpoints/EWX ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

How to Develop a Custom getText() Function for a Selenium Element?

Creating a custom Selenium getText() method that can retrieve either the node text or the node plus child text of an element is my current challenge. The default behavior of Selenium appears to utilize the Xpath .//string() method which includes the text o ...

Pagination in DynamoDB: Moving forward and backward through your data

Currently, I am utilizing DynamoDB in combination with NodeJS to display a list of objects on the user interface. Given that DynamoDB can only process 1MB of data at a time, I have opted to implement pagination. This allows users to navigate between pages ...

I am seeking a way to conceal list elements according to a specified string input using JavaScript

Looking at the list items inside this div: <div class="container"> <h2>Vanishing Act Game</h2> <div> <li class="list-group-item go" id="item">Door#1</li> <li class="list-group-item go" id="it ...

The issue of empty req.body in POST middleware with Medusa.JS

Feeling completely frustrated with this issue. Grateful in advance to anyone who can lend a hand. Any insights on why req.body is showing up empty? Medusa.JS should be utilizing bodyParser by default, correct? It was functioning fine earlier today but now ...

Ways to successfully pass multiple parameters in Nuxt

Within Nuxt.js, when working with the code in pages/posts/_id.vue, it looks like this: <template> ...

Handling OnClick events in D3 with Websocket Integration

My goal is to implement a Websocket in JavaScript that transmits a variable obtained when clicking on a node in a D3 chart. While I have made progress using static data, I'm struggling with initiating the code upon node click to retrieve the "user inf ...

Modify path and refresh display upon ajax call to node server

Recently, I made the decision to utilize a Node server as a proxy for making API calls to third-party public APIs from my front end. After successfully sending a request to my Node endpoint and then to the third-party API, I received the expected response. ...

How to easily retrieve additional data and update a document using Meteor

I'm feeling a bit lost on the best approach for obtaining additional data, particularly using an API, and adding it to the existing list. Imagine we're implementing either an infinite scroll or a 'load more' button, when that action oc ...

The redirect function is failing to carry the "req" parameter

Express Routes Troubleshooting app.get('/auth/google/redirect', passport.authenticate('google'), (req, res) => { console.log('req.user:', req.user) //>>>>>Outputs {username: 'bob', id: '.. ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

Encountered a problem while assigning a function to a variable

I'm currently working with a function that retrieves images based on a search query. Here's the code: function getImage(query){ var serach_title = query.replace(/\ /g, '+'); var imgUrl = "https://ajax.googleapis.com/ajax/s ...

Guide on keeping your MongoDB collection up-to-date with Mongoose

I'm currently facing an issue while working on a project. My goal is to build a MongoDB database where I can store dates and YouTube video links. I've chosen to use Mongoose as my ORM. The problem I'm encountering is that while I can create ...

Is there a way to divide all the characters within a string, excluding the sequence " "?

My issue (resolved) I've been working on an animation where each letter appears sequentially, but I encountered a problem. In order to transform the letters properly, I had to wrap my span tags in a flex div because using inline-block didn't all ...

Can Angular components be used to replace a segment of a string?

Looking to integrate a tag system in Angular similar to Instagram or Twitter. Unsure of the correct approach for this task. Consider a string like: Hello #xyz how are you doing?. I aim to replace #xyz with <tag-component [input]="xyz">&l ...

Component loader with dynamic rendering for multiple components

Currently, I am in search of a method to dynamically render components within my Angular application. While exploring various options, I came across the concept of dynamic component loading in Angular (refer to https://angular.io/guide/dynamic-component-lo ...

Dealing with a throw er; uncaught 'err' event while configuring a server with nodemon

I am currently in the process of setting up my local server using node.js and nodemon. Initially, everything runs smoothly on localhost, but as soon as I refresh the page or navigate to another page, the server crashes with an 'unhandled error event&a ...