Skip to content

Instantly share code, notes, and snippets.

@drabbytux
Last active November 27, 2020 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drabbytux/881d697179b9708f1bcb582f33c59307 to your computer and use it in GitHub Desktop.
Save drabbytux/881d697179b9708f1bcb582f33c59307 to your computer and use it in GitHub Desktop.
Limit cart quantities to in-stock items
layout title description nav
default
Limit cart quantities to in-stock items
You can prevent your customers from adding larger quantities to the cart than you have in stock at your online Shopify store.
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) {
      e.preventDefault();
      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 {
            alert(response);
          }
        }
      } );
    });
    
    {% endraw %}
@gerolu
Copy link

gerolu commented Nov 27, 2020

Great. Thanks for your work. Please explaine me one more thing. Is it possible and how if it is to change system massage from "You can't..." to "You can buy ..." with number of inventory for this variant?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment