Variant Issue in Ella Theme

Variant Issue in Ella Theme

Creativenexus
Shopify Partner
2 0 0

I'm experiencing an issue on my website related to variant selection. Here's the problem:

When I change variants, the prices were not updating based on the selected variant. I resolved this issue with a custom JavaScript script, and now it's working perfectly. However, there's a new issue:

  • If a product is out of stock, and there are two variant options (e.g., color and size), with each having two choices, the following occurs:
    • When I select the second option for the color variant, the size variant automatically resets to the first option.

This behavior is only observed when the product is out of stock. It works perfectly fine when the product is in stock.

Here's the website URL and the JavaScript code I'm using:
[Website URL]

 

<script>

document.addEventListener('DOMContentLoaded', function () {
// Get all the product option selectors dynamically
const optionSelectors = document.querySelectorAll('[name^="options"]'); // Selects all variation dropdowns/buttons

if (optionSelectors.length > 0) {
const productJSON = document.querySelector('[type="application/json"]');
if (!productJSON) return; // Exit if no product data available

// Parse the product data from the JSON
const productData = JSON.parse(productJSON.textContent);

// Function to update the product variant based on selected options
const updateVariant = () => {
const selectedOptions = Array.from(optionSelectors).map(selector => selector.value);

// Find the matching variant
const matchingVariant = productData.variants.find(variant => {
return variant.options.every((option, index) => option === selectedOptions[index]);
});

if (matchingVariant) {
// Update the product form with the correct variant ID
const variantInput = document.querySelector('[name="id"]');
if (variantInput) variantInput.value = matchingVariant.id;

// Optionally update prices, images, etc.
console.log('Matching Variant:', matchingVariant);
}
};

// Attach change event listeners to each option selector
optionSelectors.forEach(selector => {
selector.addEventListener('change', updateVariant);
});
}
});

</script>

 

Please assist me in resolving this issue.

Replies 0 (0)