Как получить все значения(количество товара * цена товара) из цикла forEach, сложить их и вывести общую сумму вне этого цикла

const listItems = document.querySelector('.list')
const products = [{
    inpVal: 1,
    title: 'nachos',
    value: '30'
  },
  {
    inpVal: 0,
    title: 'guacamole',
    value: '40'
  },
  {

    inpVal: 1,
    title: 'potatos chips',
    value: '5'
  },
]


function getListItems() {
  for (let index = 0; index < products.length; index++) {
    listItems.insertAdjacentHTML('beforeend', itemLi(products[index], index))
    //console.log(products[index].title)
  }
}


function itemLi(item, index) {
  return `
    <li class="block menu-dop__item">
    <div>${item.title}</div>
    <span class="price" data-price="${item.value}">${item.value}</span><span>$</span></div>
    <button class="btn" data-type="minus" data-index="${index}">-</button>
        <input class="extras inpElement hidden" data-val="7" data-min="0" data-max="10" type="text" placeholder="количество товаров" value="${item.inpVal}" data-index="">
        <button class="btn" data-type="plus" data-index="${index}">+</button>
       </li>`
}
getListItems()
const inputElement = document.querySelectorAll('.inpElement')
const btns = document.querySelectorAll('.btn')
const blocks = document.querySelectorAll('.block')
blocks.forEach(el => {
  el.addEventListener('click', (e) => {
    const priceDiv = el.querySelector('.price');
    let price = Number(priceDiv.dataset.price)
    const inp = el.querySelector('.inpElement');
    let oldValue = Number(inp.value)
    let min = inp.dataset.min
    let max = inp.dataset.max

    if (e.target.dataset.type) {
      const type = e.target.dataset.type

      if (type === 'plus') {
        inp.classList.add('visible')
        if (oldValue < max) {
          let newVal = oldValue + 1
          let quant = price * newVal
          price = quant
          oldValue = newVal
          inp.value = newVal
          priceDiv.innerHTML = `<span>${quant}</span>`

        }
      } else if (type === 'minus') {

        if (oldValue <= 1) {
          inp.classList.remove('visible')
          newVal = oldValue
        } else if (oldValue > min) {
          let newVal = oldValue - 1
          let quant = price * newVal
          price = quant
          oldValue = newVal
          inp.value = newVal

          if (newVal != 0) {
            priceDiv.innerHTML = `<span>${quant}</span>`
          }
        }
      }
    }
  })
})
<ul class="list menu-dop__list"></ul>


Ответы (2 шт):

Автор решения: Andre

У вас есть переменная quant, которая, как я понял, является количеством*цену. Создайте новую переменную за циклом forEach и прибавляйте к этой переменной переменную quant, затем после цикла выводите эту новую переменную куда вам нужно.

→ Ссылка
Автор решения: EzioMercer

Немного переписал ваш код:

  • Вынес шаблон в тег template. Да, код стал больше, но писать HTML код внутри HTML файла удобнее чем внутри JS файла. Если нет возможности в HTML файле создавать template-ы, то смело можете возвращать ваш код с строчным вариантом

  • Добавление множества li сделал через DocumentFragment с помощью createDocumentFragment

  • Множество событий оптимизировал с помощью Event delegation

  • Не очень понял логику с классом visible потому не включил его в свой код, но вы с лёгкостью можете это сделать сами

  • Так же вы почему-то смотрите на значение oldValue, хотя по идее надо смотреть на новое значение и для него проверять условия, т.к. если старое значение там стоит, значит оно верное по идее и не нужно для него писать дополнительные проверки

  • Сделал input-ы доступными только для чтения. Т.к. у вас input-ы текстовые, то есть риск того что туда напишут неправильные данные, а потому сделать их доступными только для чтения, показалось логичным. Так же вы можете использовать type="number" чтобы лишний раз дать понять пользователю, что вы ожидаете на вход число

  • Добавил подсчёт суммы, после каждого изменения и в самом начале

const products = [{
    inpVal: 1,
    title: 'nachos',
    value: '30'
  },
  {
    inpVal: 0,
    title: 'guacamole',
    value: '40'
  },
  {

    inpVal: 1,
    title: 'potatos chips',
    value: '5'
  },
];

let sum = 0;

const listItems = document.querySelector('.list');
const itemTemplate = document.querySelector('#item-template');

function getListItems() {
  const fragment = document.createDocumentFragment();
  
  for (let i = 0; i < products.length; ++i) {
    fragment.append(itemLi(products[i], i));
  }
  
  listItems.append(fragment);
}


function itemLi(item, index) {
    const {inpVal, title, value} = item;
    const li = itemTemplate.content.cloneNode(true);
    
    li.querySelector('.title').prepend(title);
    
    const priceEl = li.querySelector('.price');
    
    priceEl.dataset.price = value;
    
    const cost = value * inpVal;
    
    priceEl.textContent = cost;
    sum += cost;
    
    li.querySelector('[data-type="minus"]').dataset.index = index;
    
    const input = li.querySelector('input');
    
    input.value = inpVal;
    input.dataset.index = index;
    
    li.querySelector('[data-type="plus"]').dataset.index = index;
    
    return li;
}

getListItems();

listItems.addEventListener('click', e => {
  const target = e.target;
  
  if (!target.classList.contains('btn')) return;
  
  const li = target.parentElement;
  
  const input = li.querySelector('input');
  const oldCount = Number(input.value);
  const min = Number(input.dataset.min);
  const max = Number(input.dataset.max);
  
  const changer = target.dataset.type === 'plus' ? 1 : -1;
  
  const newCount = oldCount + changer;
  
  if (newCount < min || newCount > max) return;
  
  const priceEl = li.querySelector('.price');
  const price = Number(priceEl.dataset.price);
  
  input.value = newCount;
  priceEl.textContent = newCount * price;
  
  sum += changer * price;
  
  console.log(sum);
});
body {
  background-color: gray;
}
<ul class="list menu-dop__list"></ul>

<template id="item-template">
  <li class="block menu-dop__item">
    <div class="title"></div>
      <!-- Title -->
    <span class="price" data-price="<!-- Item value -->"><!-- Item value --></span>
    <span>$</span>
    
    <button class="btn" data-type="minus" data-index="<!-- Index -->">-</button>
    <input
      class="extras inpElement hidden"
      readonly
      data-val="7"
      data-min="0"
      data-max="10"
      type="text"
      placeholder="количество товаров"
      data-index="<!-- Index -->"
    >
    <button class="btn" data-type="plus" data-index="<!-- Index -->">+</button>
  </li>
</template>

Если будут вопросы, то не стесняйтесь задавать их!

→ Ссылка