简体   繁体   中英

how to get change total sum foreach

I have a code cannot get inner foreach total sum

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

    a.onchange = function() {
      const numTot = parseInt(a.value);
      const itemTot = 0;

      numTot.forEach(eachItem => {
        itemTot += itemTot;
      });
    };
  });
</script>

the second foreach is no function

const numTot = parseInt(a.value);

numTot is int,not array -> cant forEach

You can store the previous value of each input in the closure and add the delta to the total sum each time it changes.

const opSelect = document.querySelectorAll('.op .qltbox');
let sum = 0;
opSelect.forEach(opSelect => {
    const a = opSelect.querySelector('input[type=text]');
    let prev = 0;
    a.onchange = function() {
        let curr = +a.value;
        sum += curr - prev;
        prev = curr;
        console.log('total sum:', sum);
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM