I am now making a simple webshop and I am implementing a shopping cart in javascript. I want to call my function productTotalPrice() which gives me the total price of that item (price of the item * quantity). I want to update the total price every time I click a button(increment button, decrement and delete button). Here's my productTotalPrice(). I started Javascript 3 days ago so any advise would be nice!
// total price per item calculator
function productTotalPrice() {
var cartItems = document.getElementsByClassName("cart-list");
var products = document.getElementsByClassName("product");
for (var i = 0; i <= cartItems.length; i++) {
// Please improve this if you can!!
var product = products[i];
var productdetail = product.children[2];
var priceElement = productdetail.children[3];
var productPrice = parseFloat(priceElement.innerText.replace("€", ""));
var productQuantity = document.getElementsByClassName("cost")[i].value;
var priceXquantity = productPrice * productQuantity;
var price = "€" + priceXquantity;
document.getElementsByClassName("price")[i].innerText = price;
}
}
var removeCartItemButtons = document.getElementsByClassName('vknop');
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i];
button.addEventListener('click', function(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.parentElement.remove();
productTotalPrice();
})
}
<div class="cart-list">
<!-- Product #1 -->
<div class="product">
<div>
<p class="vknop" type="button">X</p>
</div>
<div class="image">
<img src="images/mask1.png" alt="mask">
</div>
<div class="detail">
<p>Mask1</p>
<p>Color:Green</p>
<p>size:S</p>
<p>€10.99</p>
</div>
<div class="quantity">
<button class="add" type="button" name="button">
+
</button>
<input class="cost" type="text" name="amount" value="1" id="qtybox">
<button class="remove" type="button" name="button">
-
</button>
</div>
<div class="price"></div>
</div>
The implemented logic of your code is correct , the buttons work as intented
but the problem of having to refresh page everytime you click a button to display a change in cart value or no of items can be fixed by using Asynchronous Javascript ( AJAX ) rather than basic JS .
YOur code should be modified to take asynchronous inputs from the background or not ( in case when user scrolls through the page rather than interacting with the page)
You can learn more about AJAX here