Reputation: 149
I am trying to update the product price when a variant is selected. So far i have the below; but just cant get it to work.
I have added this script to the theme.liquid
{{ 'option_selection.js' | shopify_asset_url | script_tag }}
I have the price in the product-template.liquid
<div class="product-price"><span id="price-field">{{ product.price | money }}</span></div>
<select
v-model="form.id"
name="id" id="variant-id"
class="minimal mt-2 mb-2 {% if hide_default_title %}hidden{% endif %}">
{% for variant in product.variants %}
{% if variant.available %}
<option
{% if variant == current_variant %}selected="selected"{% endif %}
{% unless variant.available %}disabled="disabled"{% endunless %}
data-inventory-quantity="{{ variant.inventory_quantity }}"
data-price="{{ variant.price | money | strip_html }}"
value="{{ variant.id }}"
class="js-variant-radio">{{ variant.title }}
</option>
{% endif %}
{% endfor %}
</select>
And the callback function here
<script>
// <![CDATA[
var selectCallback = function(variant, selector) {
if (variant) {
if (variant.available) {
// Selected a valid variant that is available.
$('#add').removeClass('disabled').removeAttr('disabled').val('Add to Cart').fadeTo(200,1);
} else {
// Variant is sold out.
$('#add').val('Sold Out').addClass('disabled').attr('disabled', 'disabled').fadeTo(200,0.5);
}
// Whether the variant is in stock or not, we can update the price and compare at price.
if ( variant.compare_at_price > variant.price ) {
$('#price-field').html('<span class="product-price on-sale">'+ Shopify.formatMoney(variant.price, "") +'</span>'+' <s class="product-compare-price">'+Shopify.formatMoney(variant.compare_at_price, "")+ '</s>');
} else {
$('#price-field').html('<span class="product-price">'+ Shopify.formatMoney(variant.price, "") + '</span>' );
}
} else {
// variant doesn't exist.
$('#add').val('Unavailable').addClass('disabled').attr('disabled', 'disabled').fadeTo(200,0.5);
}
}
// initialize multi selector for product
jQuery(function($) {
new Shopify.OptionSelectors("variant-id", { product: , onVariantSelected: selectCallback });
});
// ]]>
</script>
Upvotes: 0
Views: 1656
Reputation: 3248
Looking at the code, it looks like you're just missing a product object when you try to initialize the Shopify.OptionSelectors
new Shopify.OptionSelectors("variant-id", { product: , onVariantSelected: selectCallback });
Try adding the product object to this line to see if that fixes the problem. The updated line should look like this:
new Shopify.OptionSelectors("variant-id", { product: {{ product | json }}, onVariantSelected: selectCallback });
Upvotes: 1