0

Добрый день, подскажите, пожалуйста,как сделать такую тему -

есть N-ое количество чекбоксов, напротив каждого чекбокса div-block в котором указана цена, нужно сделать так,чтобы внизу выводилась суммарная стоимость отмеченных продуктов.

1 ответ 1

1

Вот так?

document.addEventListener('DOMContentLoaded', e => {
  Array.from(document.querySelectorAll('.item input')).map(e => e.addEventListener('change', handler));
});

function handler(){
  let cost      = parseFloat(this.dataset.price),
      view      = document.querySelector('#totalCost'),
      totalCost = parseFloat(view.textContent.substring(1)),
      newCost   = '';
  
  if(this.checked)
    newCost = (totalCost + cost).toFixed(2);
  else
    newCost = (totalCost - cost).toFixed(2);
  
  view.textContent = `$${newCost}`;
}
.price{
  display: inline;
}
<div class='main'>
  <div class='item'>
    <label>
      <input type='checkbox' data-price='10' />
      <div class='price'>$10</div>
    </label>
  </div>
  <div class='item'>
    <label>
      <input type='checkbox' data-price='0.05' />
      <div class='price'>$0.05</div>
    </label>
  </div>
  <div class='item'>
    <label>
      <input type='checkbox' data-price='3.83' />
      <div class='price'>$3.83</div>
    </label>
  </div>
  <div class='item'>
    <label>
      <input type='checkbox' data-price='56' />
      <div class='price'>$56</div>
    </label>
  </div>
  <div class='item'>
    <label>
      <input type='checkbox' data-price='0.26' />
      <div class='price'>$0.26</div>
    </label>
  </div>
  <div class='item'>
    <label>
      <input type='checkbox' data-price='359.15' />
      <div class='price'>$359.15</div>
    </label>
  </div>
</div>
<hr />
<span>Total cost: </span><strong id='totalCost'>$0.00</strong>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.