简体   繁体   中英

Add to cart - change from a dropdown variant select with add to cart button to single add to cart button for each variant on Shopify / Liquid

I have the following code on Shopify / Liquid for adding a variant of a product to cart. I want to change it from a dropdown with an 'add to cart' button to just single buttons to add the size to cart. This would ultimately result in a number of buttons being added for each size option. My code is below:

        <form action="/cart/add" method="post" enctype="multipart/form-data" id="AddToCartForm" class="quick-add-to-cart small--hide clearfix">
          {% if product.variants.size > 1 %}
            <select id="product-select-{{ product.id }}" name='id' class="text-center">
            {% for variant in product.variants %}
            {% if variant.available %}
              <option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} data-sku="{{ variant.sku }}" value="{{ variant.id }}">{{ variant.title }}</option>
            {% else %}
              <option disabled="disabled">
              {{ variant.title }} - {{ 'products.product.sold_out' | t }}
              </option>
            {% endif %}
            {% endfor %}
            </select>
            {% else %}
              <input type="hidden" name="id" value="{{ product.variants.first.id }}" />
            {% endif %}

            {% if product.available %}
              <button type="submit" name="add" id="AddToCart" class="btn btn-mini text-center" onclick="ga('send', 'event', 'Quick Add To Cart', '{{ product.type }}', '{{ product.title }}');">Add To Cart</button>
            {% else %}
              <h6>Out of Stock</h6>
            {% endif %}
          </form>

If anyone knows how to change the above code for this request that would be amazing!

Thanks a lot.

Original format

New desired format (single button)

Yes, just convert each variant into a form with a button to add.

{%- for variant in product.variants -%}
  {%- unless variant.available -%}
    {%- continue -%}
  {%- endunless -%}

  <form action="/cart/add" method="post" enctype="multipart/form-data" id="AddToCartForm" class="quick-add-to-cart small--hide clearfix">
    <input type="hidden" name="id" value="{{ variant.id }}" />
    <button type="submit" name="add" id="AddToCart" class="btn btn-mini text-center" onclick="ga('send', 'event', 'Quick Add To Cart', '{{ product.type }}', '{{ product.title }}');">Add {{ variant.title }}</button>
  </form>
{%- endfor -%}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM