JSFiddle - React, Tailwind, and code Playground
HTML
<form action=""></form>
<div class="result">
<div id="totalWeight"></div>
<div id="totalVolume"></div>
<div id="totalPrice"></div>
<div id="totalCount"></div>
</div>
CSS
label {
display: block;
font-weight: bold;
}
.btnGroup {
outline: dashed 1px gray;
margin: 10px;
padding: 5px;
}
.result div {
border: solid 2px lightgray;
}
JavaScript
;(function(){
const form = document.querySelector('form')
const price = 10
const products = [
{
name: 'товар1',
weight: 0.100,
volume: 0.150,
price: 23,
},
{
name: 'другой товар',
weight: 0.240,
volume: 0.250,
price: 344,
},
{
name: 'Третий товар',
weight: 0.750,
volume: 0.367,
price: 1.56,
},
]
function generateForm() {
products.forEach(product => {
form.innerHTML += `
<div class="btnGroup">
<label>${product.name}<label>
<button class="minus">-</button>
<input type="number" value="0" min="0">
<button class="plus">+</button>
</div>`
})
}
function calculate() {
const form = this
let totalVolume = 0,
totalWeight = 0,
totalPrice = 0,
totalCount = 0
$('input', this).each(function(i){
let count = parseInt(this.value, 10)
totalCount += count
totalVolume += count * products[i].volume
totalWeight += count * products[i].weight
totalPrice += count * products[i].price
})
$('.result #totalCount').html(`Всего ${totalCount} штук`)
$('.result #totalVolume').html(`Вы израсходовали всего ${totalVolume}мл.`)
$('.result #totalPrice').html(`Вы сегодня продали товаров на сумму ${totalPrice}р.`)
$('.result #totalWeight').html(`Вы сегодня ${totalWeight} гр. товаров`)
}
function increase(evt) {
evt.preventDefault()
let $input = $(this).closest('.btnGroup').find('input')
$input.val( parseInt($input.val()) + 1)
$input.change()
}
function decrease(evt) {
evt.preventDefault()
let $input = $(this).closest('.btnGroup').find('input')
$input.val( parseInt($input.val()) - 1)
$input.change()
}
$('form').on('input change', calculate)
$('form').on('click', '.plus', increase)
$('form').on('click', '.minus', decrease)
generateForm()
})();