show/hide drop down using ajax on shopify product page
show/hide drop down using ajax on shopify product page
Im trying to show and hide a dropdown on my shopify product page if one of the product variants = 9ct Gold.
here is the code I am using so far. The problem I am having is with the API URL for shopify I assume. I cant work out what URL to use for shopify variants on the frontend.
At the moment nothing is showing and I cant work out why.
<script>
document.addEventListener('DOMContentLoaded', function() {
var productId = '{{ product.id }}'; // Access the current product ID with Liquid
var bandWidthSelect = document.getElementById('band-width');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://mystoreurl.myshopify.com/products/' + productId + '.json');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
var variants = response.product.variants;
var selectedVariant = variants.find(function(variant) {
return variant.option1 === '9ct Gold';
});
if (selectedVariant) {
var bandWidthOptions = selectedVariant.metafields.custom.band_widths.split(',');
bandWidthSelect.innerHTML = '<option value="">Select Band Width</option>';
for (var i = 0; i < bandWidthOptions.length; i++) {
var option = document.createElement('option');
option.value = bandWidthOptions[i].trim();
option.textContent = bandWidthOptions[i].trim();
bandWidthSelect.appendChild(option);
}
bandWidthSelect.style.display = 'block';
} else {
bandWidthSelect.style.display = 'none';
}
} else {
console.error('Error fetching product:', xhr.status);
}
}
};
xhr.send();
});
</script>
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand