1

I have a form with multiple rows where a user can input numbers and calculate outputs.

I can currently calculate the output of each row - the sub-total. But would like to be able to calculate all sub-totals - the total.

I'm able to log each sub-total to the console, but cannot figure out how to sum those values. Having read some similar questions I reckon I need to create an array of the values and sum those values.

Is this possible using the loop I'm currently using?

Here's what I currently have:

const rows = document.querySelectorAll('.row');
const calculate = document.querySelector('.calculate');
const output = document.querySelector('.output');

// Calculate

function calculateSubTotal() {

  rows.forEach(function(row, index){
    const input1Val = Number(row.querySelector('.input-1').value);
    const input2Val = Number(row.querySelector('.input-2').value);

    const subTotal = input1Val + input2Val;

    console.log(subTotal);
  });

}

calculate.addEventListener('click', calculateSubTotal);

Here's a pen: https://codepen.io/abbasarezoo/pen/WBXjWO?editors=1111

1 Answer 1

1

Declare a variable outside forEach and increase it inside forEach

function calculateSubTotal() {
  let total = 0;
  rows.forEach(function(row, index){
    const input1Val = Number(row.querySelector('.input-1').value);
    const input2Val = Number(row.querySelector('.input-2').value);

    const subTotal = input1Val + input2Val;

    console.log(subTotal);
    total += subTotal 
  });

}

A simplified version of your code using reduce() and map() will be

function calculateSubTotal() {
  let total = 0;
  let subTotals = rows.map(x => +x.querySelector('.input-1').value + +x.querySelector('.input-2').value)
  let total = subTotals.reduce((ac,a) => ac + a,0)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.