12/11/2016 - 7:32 PM

Limit cart quantities to in-stock items

Limit cart quantities to in-stock items

layout: default title: Limit cart quantities to in-stock items description: You can prevent your customers from adding larger quantities to the cart than you have in stock at your online Shopify store.

difficulty: novice

nav: group: products

{% block "note-information" %} This article is only relevant to you if your Shopify theme brings your customers to the cart page when an item is added to the cart. It will be helpful if you use the New Standard, Minimal or React theme, for example. {% endblock %}

The problem

On the product page, Shopify shows an item as still available when all of its inventory has been added to the cart. Adding more of the item to the cart with a regular POST request — not Ajax — will not produce an error, and the requested quantity will be added to the cart. At checkout, the shopper will be informed of necessary quantity adjustments. You may not want for them to wait that long to discover that the item they want is low in stock.

The fix

{% include admin_sidebar/online-themes-edit-html-css.html %}

  1. On the left, under Templates, click product.liquid to open your product template in the code editor.

  2. At the very bottom of your theme.js file in Assets, add the following:

    {% raw %}
    $(document).ready( function() { 
    jQuery('form[action="/cart/add"]').submit(function(e) {
      jQuery.ajax( {
        url: '/cart/add.js',
        type: 'post',
        dataType: 'json',
        data: jQuery(this).serialize(),
        success: function() { window.location.href = '/cart' },
        error: function(jqXHR) {
          var response = eval('(' + jqXHR.responseText + ')').description;
          if (response.slice(0,4) === 'All ') {
            jQuery('form[action="/cart/add"]').find('input[type="submit"], button[type="submit"]').val('Sold Out').addClass('disabled').attr('disabled','disabled');
            alert(response.replace('All 1 ', 'All '));
          else {
      } );
    {% endraw %}