Shopify cart page - Changing quantity input value with jQuery

Viewed 1516

I have + and - buttons in the cart layout that are changing the value of the quantity input using jQuery.

It works perfectly on the page and in the source code (quantity values changes) but it doesn't work after page refresh and doesn't get reflected on the checkout page.

Changing the quantity manually (with built-in input arrows or by typing the new amount into the field) works normally.

    $(".qty-button").on("click", function() {

    var $button = $(this);
    var oldValue = $button.parent().find("input").val();
    var newVal;

    if ($button.text() === "+") {
        newVal = parseFloat(oldValue) + 1;
    } else {
        if (oldValue > 0) {
            newVal = parseFloat(oldValue) - 1;
        } else {
            newVal = 0;
        }
    }

    $button.parent().find("input").attr('value', newVal).trigger('change');

});

It changes the value in the page source and is reflected on the cart page but does nothing in terms of functionality as it gets back to the original value on page refresh or checkout.

Any ideas?

1 Answers

Didn't know I need to fire the Shopify Cart API.

In case anyone needs it in the future, fixed with:

  <div class="cart-item-block qty-selector">
      <div class="qty-button increase" onclick="Shopify.addItem({{ item.variant.id }}, this.parentNode.querySelector('input[type=number]').value)">+</div>
      <input id="updates_{{ item.key }}" class="cart-qty-input" type="number"
             name="updates[]" value="{{ item.quantity }}" min="1" pattern="[0-9]*"
             >
      <div class="qty-button decrease" onclick="Shopify.removeItem({{ item.variant.id }}, this.parentNode.querySelector('input[type=number]').value)">-</div>
  </div>

<script>
    Shopify.addItem = async function(id,quantity){
        await $.ajax({
            method:'POST',
            url:'/cart/change.js',
            data:{ id:id, quantity:(++quantity) },
            dataType: 'json'
        })
    };
    
    Shopify.removeItem = async function(id,quantity){
        await $.ajax({
            method:'POST',
            url:'/cart/change.js',
            data:{ id:id, quantity:(--quantity) },
            dataType: 'json'
        })
    };
</script>
Related