Tips on obtaining the total sum for each change transaction

I'm struggling with a code that is not calculating the total sum properly within an inner foreach loop

<script>
  const opSelect = document.querySelectorAll('.op .qltbox');
  opSelect.forEach(op => {
    const inputElement = op.querySelector('input[type=text]');

    inputElement.onchange = function() {
      const numTotal = parseInt(inputElement.value);
      let itemTotal = 0;

      // Error occurs in this second forEach loop
      numTotal.forEach(eachItem => {
        itemTotal += eachItem;
      });
    };
  });
</script>

The issue seems to lie in the functionality of the second foreach loop

Answer №1

To optimize the efficiency of your code, it's possible to cache the previous value of each input within a closure and incrementally update the total sum with the delta on each change event.

const qualityInputs = document.querySelectorAll('.op .qltbox');
let totalSum = 0;
qualityInputs.forEach(qualityInput => {
    const inputValue = qualityInput.querySelector('input[type=text]');
    let previousValue = 0;
    inputValue.onchange = function() {
        let currentValue = +inputValue.value;
        totalSum += currentValue - previousValue;
        previousValue = currentValue;
        console.log('updated total sum:', totalSum);
    };
});

Answer №2

Let totalNum = parseInt(inputField.value);

The totalNum variable is an integer, not an array, so it cannot be iterated over with the forEach method.

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

Whenever I attempt to connect to Stripe, my code fails to execute properly

My knowledge of Javascript is limited, but I have a basic understanding. I am currently diving into learning about Stripe and testing it in a local environment with a Wordpress install. Following the Stripe documentation, I have successfully installed Node ...

Using a script to properly close HTML tags

It seems like a straightforward task, but I'm not sure where to start looking for the solution. What I'm trying to accomplish is this. I have a script that scans for the strings [gallery]. When it finds [gallery], it replaces the tag with an ima ...

Is there a way to customize the CSS for a single blog post and add a 5-star rating system without affecting other posts?

After launching my blog on Google's Blogger, I wanted to add a unique touch by incorporating a static 5-star rating system in my Books I Read Section. I thought about using CSS to customize each book post and display anywhere from 1 to 5 stars for vis ...

ng-model causing simultaneous changes to all selects

Check out this jsfiddle link Hello there, I'm encountering an issue with my application. I need to create multiple dropdowns using ng-repeat and have them all populated with the same options. The problem arises when one dropdown is changed, all ot ...

Instructions on how to determine if a client is a "desktop terminal"

So here's the deal: I have a suspicion about thin clients accessing my website. Is there a way to test if a client is a thin client without causing it to lag with JavaScript animations? I want to provide a simplified version of the site for these clie ...

Enhance your browsing experience by inputting valuable information into the

I am looking to enhance a text box by adding values. The text box already has a default value of 10, and I want to create a button that will add new text boxes with a limit of 4. My goal is to continuously add values from text box 1 to text box 4. For exa ...

JavaScript fails to function in an HTML file

I am facing an issue where my JavaScript code works perfectly in JSFiddle, but when I copy it into an HTML file, it doesn't function as expected. Despite searching through other related posts, I have been unable to find a solution for this specific pr ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...

Creating a Texture in html5 and WebGL using an ArrayBuffer

I have an image that I am retrieving on the server side and sending to the web browser through an AJAX call. I need to display this image line by line using WebGL. For example, let's consider an image with dimensions 640X480. This means there are a t ...

What is the best way to present these values with spaces in between each word?

When I use console.log(JSON.stringify(selected["1"]?.others)), the output is: ["Cars","Books","Necklaces"] On the screen, however, when displaying this data, all the words appear together without spaces. It looks li ...

The random string generator is selecting a unique string for both the server and client side

I am facing an issue with a component in Next.js (v14.2.1) where I need to display a random string while fetching data. Despite my attempts, I can't seem to maintain the same string on both server and client sides. Below is the code snippet I am curr ...

Guide on incorporating a rating and review feature into your Windows 8 store app with JavaScript and HTML

Looking for assistance on integrating a rate and review feature into a Windows 8 store app using javascript and html. Specifically, I would like to add this option to both the charm settings and the app bar. When a user clicks on it, they should be directe ...

The issue with Mongoose not properly dropping the database and closing the connection is causing unexpected behavior in Mocha tests

I encountered an issue with my tests - one passed and the other failed due to a problem with the Schema being compiled again. Error: Cannot overwrite CheckStaging model once compiled. The first test that passed: var mongoose = require('mongoose& ...

Changing the color variable of an object using an onClick function in JavaScript

I'm currently working on a simple game where users can draw using the keys W, A, S, and D. If you want to take a look at the progress I've made so far, here is a JSFiddle link. There's a collision function in the code that I no longer need, ...

Begin the process by hitting the enter key

Check out my website here! I want to enhance the functionality of my site by triggering a Google Images search when the 'enter' key is pressed, instead of just relying on a button click. This is the HTML structure: <p>Enter your search t ...

An issue has occurred: TypeError - It is impossible to access the 'forEach' property of an undefined object

Having trouble with a promise issue that I just can't seem to solve. Whenever I enter 'pizza' into the search bar and click search, the console displays an error message: TypeError: Cannot read property 'forEach' of undefined I&ap ...

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

Working with the visibility of a button using JavaScript

My goal is to toggle the visibility of a button using JavaScript. Initially, on page load, the button should be hidden. function hideButton(){ var x = document.getElementById('myDIV'); x.style.display = 'none'; } The visibilit ...

Whenever I am building a React application, I encounter a bug that states: "node:fs:1380 const result = binding.mkdir()"

Whenever I try to enter the command: create-react-app my-app --template typescript I keep encountering this error message: node:fs:1380 const result = binding.mkdir( ^ Error: EPERM: operation not permitted, mkdir 'D:\ ...

Modifying Image Source on Hover Using Jquery

Is it possible to change the source of an image on hover and then back to the original source? For example, the name of the file always remains the same, but the number changes - 1 for the original and 2 for the hover. Thank you for any advice. Code: < ...