Is it possible to force another product in Cart to match qty of first?

The below code is working, My question: Is it possible to modify this to force match qty to the trigger product being added, at a 1 to 1 ratio?

So if the customer added 5 Repreve backpacks, it would add 5 of the free straws ideally.

If not, thanks for looking anyway!

{% for item in cart.items %}
{% if item.product.title contains 'Repreve' %}
{% assign product = all_products['free-stainless-steel-straws'] %}
{% unless cart.item_count == 0 or product.empty? or product.variants.first.available == false %}
 {% assign variant_id = product.variants.first.id %}
<script>
   (function($) {     
     var cartItems = {{ cart.items | json }},         
     qtyInTheCart = 0,         
     cartUpdates = {};     
     
     for (var i=0; i<cartItems.length; i++) {       
       
     if ( cartItems[i].id === {{ variant_id }} ) {         
     qtyInTheCart = cartItems[i].quantity;         
         
     break;       }     }     
         
     if ( ( cartItems.length === 1 ) && ( qtyInTheCart > 0 ) ) {       cartUpdates = { {{ variant_id }}: 0 }     }     
       
     else if ( ( cartItems.length >= 1 ) && ( qtyInTheCart !== 1 ) ) {       cartUpdates = { {{ variant_id }}: 1 }     }     
       
     else {       return;     }     
     var params = {       type: 'POST',       url: '/cart/update.js',       data: { updates: cartUpdates },       dataType: 'json',       success: function(stuff) {          window.location.href = '/cart';       }     };     $.ajax(params);   })(jQuery); </script>  
 {% endunless %}
 {% endif %}
 {% endfor %}
 {% endif %}


Read more here: https://stackoverflow.com/questions/67010696/is-it-possible-to-force-another-product-in-cart-to-match-qty-of-first

Content Attribution

This content was originally published by Noob Pat at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: