I need to show the part number for all variant I used variant meta field for that when I switch the variant I needs to auto change. This is the code I used to show the variant part number and tried to change the variant. But every time I need to refresh the page to see the updated part number after switching the variant.
I have no idea about how to show the meta field data without refreshing the page. Can anyone help ?
{% assign selected_variant = product.selected_or_first_available_variant %}
<div class="vstock-info">{{ selected_variant.metafields.custom.part_number | default: "" }}</div>
<script>
const updateDisplayValue = (variant) => {
let displayValue = "";
if (variant.metafields.custom.part_number) {
displayValue = "Part Number: " + variant.metafields.custom.part_number;
}
const stockInfoElement = document.querySelector('.vstock-info');
stockInfoElement.textContent = displayValue;
};
const variantSelect = document.querySelector('#variant-select'); // Replace with the actual ID or selector of your variant select element
variantSelect.addEventListener('change', (event) => {
const newVariantId = event.target.value;
const newVariant = product.variants.find(variant => variant.id == newVariantId);
updateDisplayValue(newVariant);
});
// Initialize display value
updateDisplayValue(selected_variant);
</script>
Thanks