Direct add to cart button not add product on cart without select any variant

i create a function on shopify that showing add to cart button and variant select option on collection page. code are working perfectly if i select a variant and click on add to cart button if i did not select any variant and directly click on add to cart button than no product are add on cart. i want the first variant are automatically add to cart if i directly click on add to cart button. i create multiple codes some are work but it only increase the quantity of first product if i also select the different product add to cart.

<form id="add-to-cart-form" method="post" action="/cart/add">
  <select id="variant-select" class="variant-collection" name="id" onchange="selectedVariantId = this.value;">
    {% for variant in product.variants %}
      {% if variant.available %}
        <option value="{{ variant.id }}" {% if variant.title == 'Rich Chocolate' or forloop.first %}selected{% endif %}>
          {% for option in variant.options %}
            {% if forloop.first %}Flavour: {% endif %}{{ option }}{% unless forloop.last %} / {% endunless %}
          {% endfor %}
        </option>
      {% endif %}
    {% endfor %}
  </select>
  <br>
  <button class="ProductForm__AddToCart Button collection-page-button {% if product.selected_or_first_available_variant.available and use_primary_button %}Button--primary{% else %}Button--secondary{% endif %} Button--full"
    onclick="_addMeToCart1(event,this)"
    data-action="open-drawer" data-drawer-id="sidebar-cart"
    data-variant_id="{{ product.variants.first.id }}">
    {{ 'product.form.add_to_cart' | t }}
  </button>
</form>

Javascript code

function _addMeToCart1(e, el) {
    e = e || window.event;
    e.preventDefault();

    let variantId = selectedVariantId || document.querySelector('#variant-select option[selected]').value;

    if (!variantId) {
      console.error('Error: Variant ID not found');
      return;
    }

    let formData = {
      'items': [
        {
          'id': variantId,
          'quantity': 1
        }
      ]
    };

    fetch('/cart/add.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData)
    })
    .then((resp) => { 
      if (!resp.ok) {
        throw new Error('Network response was not ok');
      }
      
      return resp.json();
    })
    .then((data) => {
      document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
          bubbles: true
      }));
    })
    .catch((err) => {
      console.error('Error: ' + err);
    });
  }

To automatically add the first variant to the cart when clicking the “Add to Cart” button without selecting a variant, you can modify the JavaScript code as follows:

function _addMeToCart1(e, el) {
  e = e || window.event;
  e.preventDefault();

  let variantId = selectedVariantId || document.querySelector('#variant-select option[selected]').value;

  // If variantId is still not found, use the first available variant
  if (!variantId) {
    variantId = '{{ product.variants.first.id }}';
  }

  if (!variantId) {
    console.error('Error: Variant ID not found');
    return;
  }

  let formData = {
    'items': [
      {
        'id': variantId,
        'quantity': 1
      }
    ]
  };

  fetch('/cart/add.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(formData)
  })
    .then((resp) => {
      if (!resp.ok) {
        throw new Error('Network response was not ok');
      }

      return resp.json();
    })
    .then((data) => {
      document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
        bubbles: true
      }));
    })
    .catch((err) => {
      console.error('Error: ' + err);
    });
}

With this modification, if no variant is selected, the first available variant’s ID will be used to add it to the cart. Make sure to replace {{ product.variants.first.id }} with the actual liquid variable that represents the ID of the first variant.

Hello @vikrant1234 ,

To directly add a product to a cart without selecting any variant on Shopify, and with the default first variant, you can modify the URL for the “Add to Cart” button.

Here’s how you can do it:

Locate the “Add to Cart” button code on your product page. This code typically looks like this:

php

In the URL for the form action, add “?id={{ product.variants.first.id }}” to the end. This will add the first variant of the product to the cart by default. Here’s what the modified code looks like:

php

Copy this code and paste it into the button code.

Now, save the changes to your product page code.

Once done, when a customer clicks the “Add to Cart” button on the product page, it will add the first variant of the product to the cart by default without requiring the customer to select a variant from the dropdown menu.

Hope it helps. Let us know if you have any further issues.

Regards,

CedCommerce

1 Like

This code is working