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);
});
}