'update Shopify quantity selector using Javascript/jquery output

I am currently creating a flooring website which requires a calculator on the products page. The idea of this is to allow the user to input the length and width of the room, once they have done this the calculator will then tell the user how many packs of the selected flooring they will need.

I now need this outputted number of packs to auto populate the Shopify quantity selector. For example if the user inputs the room length and width and the calculator says that they need 18 packs of the select flooring, I need the quantity selector to update to 18 via AJAX?

My current input code is below:

<div class="quantity-selector quantity-selector--product">
   <button type="button" class="quantity-selector__button" data-action="decrease-picker-quantity" aria-label="{{ 'cart.items.decrease_quantity' | t }}" title="{{ 'cart.items.decrease_quantity' | t }}">{% render 'icon', icon: 'minus' %}</button>
   <input id="updatingqty" name="quantity" aria-label="{{ 'product.form.quantity' | t }}" class="quantity-selector__value" inputmode="numeric" value="1" size="3">
   <button type="button" class="quantity-selector__button" data-action="increase-picker-quantity" aria-label="{{ 'cart.items.increase_quantity' | t }}" title="{{ 'cart.items.increase_quantity' | t }}">{% render 'icon', icon: 'plus' %}</button>
</div>

Thanks all, any help is greatly appreciated.



Solution 1:[1]

You need to update line item quantity using Cart API

Source: Cart API reference

Use the POST /{locale}/cart/update.js endpoint to update the cart's line item quantities, note, or attributes. You can submit a serialized cart form, or submit separate updates to a cart's line items, note, or attributes.

Update line item quantities

To update line item quantities, you can make a POST request with an updates object. The updates object must contain key-value pairs where the the value is the desired quantity, and the key is one of the following:

The line item's variant_id

The line item's key

jQuery.post(window.Shopify.routes.root + 'cart/update.js', {
  updates: {
    794864053: 2,
    794864233: 3
  }
});

A cart can have multiple line items that share the same variant_id. For example, when variants have different line item properties, or automatic discounts create variants at different prices. Because of this, it's recommended to use the line item key to ensure that you're only changing the intended line item.

The following POST request yields the same result:

jQuery.post(window.Shopify.routes.root + 'cart/update.js',
  "updates[794864053]=2&updates[794864233]=3"
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TwistedOwl