HTML
<form action="">
<div class="product">
<label class="price" for="content1"> $12</label>
<input value="0" id="content1" class="num" type="number">
</div>
<div class="product">
<label class="price" for="content2"> $6</label>
<input value="0" id="content2" class="num" type="number">
</div>
<Button type="button" id="buy">BUY</Button>
</form>
<div>
<div style="display: flex; align-items: center; justify-content: center; font-size: 1.8rem;"><div></div>
<div style="font-weight: 800; margin: 10px;">==></div>
<div id="total" style="font-size: 2rem; font-weight: 900;"> </div>
<div style="font-weight: 800; margin: 10px;"> <== </div>
</div>
Pug
form(action='')
.product
label.price(for='content1') $12
input#content1.num(value='0' type='number')
.product
label.price(for='content2') $6
input#content2.num(value='0' type='number')
button#buy(type='button') BUY
div
div(style='display: flex; align-items: center; justify-content: center; font-size: 1.8rem;')
div
div(style='font-weight: 800; margin: 10px;') ==>
#total(style='font-size: 2rem; font-weight: 900;')
div(style='font-weight: 800; margin: 10px;') <==
JavaScript
const buy = document.getElementById("buy"); //the button
buy.addEventListener("click", (eo) => {
const allProd = document.querySelectorAll(".product"); //products with prices in label
const totalqua = document.getElementById("total"); //total price place
let total = 0
allProd.forEach((item) => {
const price = Number(item.getElementsByClassName("price")[0].innerText.replace("$", ""))
const num = Number(item.getElementsByClassName("num")[0].value)
total = total+(price * num)
});
totalqua.innerText = `$${total}`
});
A Simple Explanation
If you Want To do It yourself
- get all products // example queryselectorAll
- let total = 0
- for Each item
- const price=Number( item.... // get price number and convert it to number
- const quantity=Number( item.... // get quantity number
- total = total + (price*quantity)
- total = total .toFixed(2)
- element.innerText=` $ ${ total } `