All things Shopify and commerce
Hi All,
I am quite new in Shopify and I hope someone can help me with an idea.
I am trying to enhance the cart functionality by integrating product add-ons stored in metafields. I’ve updated my Liquid template to display these add-ons, but I need help with the JavaScript to handle add-on selections and update the cart total dynamically.
Here's a brief overview of my setup:
Liquid Template: Displays add-ons for each cart item using metafields.
Javascript: Needs to update the cart total when add-ons are selected or deselected.
I'd appreciate any guidance or examples on implementing the JavaScript part, especially for updating the cart total and handling interactions with Shopify's AJAX API if necessary.
Thanks in advance for your help!
Hi,
Please share your store url. If you want you can contact us details given at Signature
Also, the UI I currently made in a copy of the theme and looks like this:
This is what I have done so far:
{{ 'component-cart-addons.css' | asset_url | stylesheet_tag }}
<div class="cart-addons">
<h2 class="cart-addons__title">Enhancements</h2>
{% for item in cart.items %}
{% assign product_addons_metafield = item.variant.metafields.product_add_ons.addon.value %}
<ul class="cart-addons-list" id="addon-checkboxes">
{% if product_addons_metafield %}
{% for addon in product_addons_metafield %}
<li class="cart-addon">
<div class="cart-addon__details">
<h4 class="cart-addon__title">{{ addon.title.value }}</h4>
{% assign description = addon.description | metafield_tag %}
<p class="cart-addon__description">{{ description }}</p>
</div>
<div class="cart-addon__right">
<label for="addon-checkbox-{{ forloop.index }}" class="cart-addon__label">
Add for {{ addon.price.value | money }}
</label>
<input
type="checkbox"
id="addon-checkbox-{{ forloop.index }}"
class="cart-upsell-checkbox"
data-price="{{ addon.price.value }}"
data-variant-id="{{ item.variant.id }}"
data-enhancement-name="{{ addon.title }}"
>
</div>
</li>
{% endfor %}
{% else %}
<p>No add-ons available for this product.</p>
{% endif %}
</ul>
{% endfor %}
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const checkboxes = document.querySelectorAll('.cart-upsell-checkbox');
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
const price = parseFloat(this.dataset.price);
const variantId = this.dataset.variantId;
const enhancementName = this.dataset.enhancementName;
console.log('Checkbox changed:', { variantId, price, enhancementName });
// Calculate the current cart total price
let currentTotal = {{ cart.total_price }}
// Adjust the total price based on whether the checkbox is checked or unchecked
if (this.checked) {
currentTotal += price;
} else {
currentTotal -= price;
}
// Update the cart total using AJAX
updateCartTotalViaAjax(currentTotal);
});
});
function updateCartTotalViaAjax(newTotal) {
// Prepare the data to send
var requestData = JSON.stringify({ total_price: newTotal });
console.log('Request Data:', requestData);
// Send the AJAX request to update the cart total
var xhr = new XMLHttpRequest();
xhr.open('POST', '/cart/update.js', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var updatedCart = JSON.parse(xhr.responseText);
console.log('Cart updated successfully via AJAX:', updatedCart);
// Log the updated total price from Shopify's response
console.log('Updated Total Price:', updatedCart.total_price);
} else {
console.error('Error updating cart via AJAX:', xhr.statusText);
console.log('Response:', xhr.responseText); // Log the full response for debugging
}
};
xhr.onerror = function() {
console.error('Request failed');
// Handle error
};
xhr.send(requestData); // Send the prepared JSON stringified data
}
});
</script>
Shopify and our financial partners regularly review and update verification requiremen...
By Jacqui Mar 14, 2025Unlock the potential of marketing on your business growth with Shopify Academy's late...
By Shopify Mar 12, 2025Learn how to increase conversion rates in every stage of the customer journey by enroll...
By Shopify Mar 5, 2025