Hello! I need some help with calculating the total price in my product template. There will be an “add to cart” button with a quantity input. My prices of products come from a ecommerce collection. How can i display the (CMS PRICE * USER INPUT QUANTITY) total? This seems like a really easy thing to do but i’m very new to coding. Thanks!
Got it working. Defined the quantity input class as “quantity-input”, the price taken from a cms collection as “product-price” and the total price text block as “total-price” Then added a custom script in the footer of my page and pasted in a script that AI gave me:
<script>
document.addEventListener('DOMContentLoaded', function() {
var quantityInput = document.querySelector('.quantity-input');
var productPrice = document.querySelector('.product-price').textContent;
var totalPriceDisplay = document.querySelector('.total-price');
// Ensure the price is in a proper number format
var price = parseFloat(productPrice.replace(/[^0-9.-]+/g,""));
// Update total price function
function updateTotalPrice() {
var quantity = quantityInput.value;
var totalPrice = price * quantity;
// Prepend the dollar symbol to the total price
totalPriceDisplay.textContent = '$' + totalPrice.toFixed(2); // Rounds to 2 decimal places and updates the total price display with a dollar symbol
}
// Event listener for changes in the quantity input
quantityInput.addEventListener('change', updateTotalPrice);
// Initial update in case the default quantity is not 1
updateTotalPrice();
});
</script>
This seems to work! Hope it helps somebody else too.