How to check contents of cart after a change has been made to it.

SquareMarket
Tourist
7 0 0

I have a form that represents the cart in my cart-drawer.liquid file in the theme im using.  We have a function triggered in the onsubmit that goes to the theme.liquid and checks if there are items including more than one collection in the card. If there are, we return false, and stop the cart from submitting.

 

At this point, a user will remove the items from the cart, and we want to reset the submit button if the function doesnt return false. But how do we listen for a change in the cart?

 

<form id="CartDrawerForm" action="{{ routes.cart_url }}" method="post" novalidate class="drawer__contents" onsubmit="return validateItems();">.  <--- this is where we make our call

 

This is the function we call in the theme.liquid to see if theres items spanning more than one collection

 

    function validateItems() {
    
    
    let supplierArray = [];
    let result;
    
    
	$.ajax({
  		url: '/cart.js',
  		async: false,
  		dataType: 'json',
  		success: function (cart) {
         supplierArray = cart.items.map(a => a.vendor);
         result = supplierArray.every((val, i, arr) => val == arr[0]);
  		}
	});
      
     
      if(result === false) {
        alert("All items in the cart must belong to the same supplier. Please remove the items");
   
		return false;
      } 
}
 

 

So the question is how do we recheck when something in the cart has changed, and we want to run validateItems() again?

0 Likes