Discuss and resolve questions on Liquid, JavaScript, themes, sales channels, and site speed enhancements.
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:
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.
Hey Community! As we jump into 2025, we want to give a big shout-out to all of you wh...
By JasonH Jan 7, 2025Hey Community! As the holiday season unfolds, we want to extend heartfelt thanks to a...
By JasonH Dec 6, 2024Dropshipping, a high-growth, $226 billion-dollar industry, remains a highly dynamic bus...
By JasonH Nov 27, 2024