How do I show, in a product collection, the amount of products that's already in my cart

njiels
Visitor
2 0 0

 I am trying to create a add to cart button with incrementors to create a smoother experience (picture for reference).

Screenshot 2021-04-24 at 11.31.21.png

The little box in the button should corresponded with the amount of ordered items already in the cart. This will make the experience less confusing, given that the counter will restart at a refresh. To try to achieve this I have used:

{% for item in cart.items %}
    	{% case item.id %}
    	{% when product.id %}
    		{{item.quantity}}
    	{% endcase %}
    {% endfor %}

 And

{% for item in cart.items %}
    	{% if item.id == product.id %}
    		{% assign quantity = item.quantity %}
    	{% endif %}
    {% endfor %}
    
    {%- if quantity >= 0 -%}
    	{{ quantity }}
    {%- else -%}
    	0
    {%- endif -%}

 

It seems to me that liquid is unable to compare these two variables/object data's with each other. To give a little more context, this code is placed in a snippet.

Replies 3 (3)

Jon_Chambers
Excursionist
27 2 2

Hi.

I would use Javascript and CartJS to get the current Qty.

Here is function that will return the current qty in the cart.
Plus you could add some validation for negative and max.

 

    function getQty(_sku) {
        for (let i = 0; i < CartJS.cart.items.length; i++) {
            let _item = CartJS.cart.items[i];
            // console.log(_item);
            if (_sku.toString() == _item.sku.toString()) {
                return _item.quantity;
            }
        }
        return 0;
    }

 

From your snippet looks like you are code savvy so I kept it brief.
If you need further explanation let me know.

Regards,

Jon

 

 

njiels
Visitor
2 0 0

Hi Jon,

Thanks for your tip and sorry for my late response.

I've tried to implement CartJS but get the following error: Uncaught ReferenceError: CartJS is not defined

I reckon this is because I am editing shopify's Debut theme which might not have jQuery installed. I can't quite see if either jquery or cartjs is installed in this theme and I actually rather avoid calling jQuery for this feature only, because of performance reasons. Is this the only way to do this or is there maybe a vanilla alternative to cart.js?

I might try to compare data of the order with information from the {{ cart | json }} object, but I haven't found a way to decrease the orders when - is pressed.

Jon_Chambers
Excursionist
27 2 2

Here you go.

I have it in the  <head> area.

<!------------------------------------------------------------------------------------------ Cart JS -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/shopify-cartjs/0.4.1/cart.min.js"></script>
<script type="text/javascript">
    jQuery(function () {
        CartJS.init({{ cart | json }});
    });
</script>