I am developing a store in Sopify and I have a custom section in which i have selector for choosing variants and I also have a variant image shown next to it. What I want to make is that when I choose a variant, the featured image also changes to the featured image of that selected variant, but i don’t know how should I get it’s attribute.
This is the code I have:
$('.upsell-variants__selector').click(function(){
var main_img = $(this).attr('data-variant');
$('.product__upsell-image img').attr('src', main_img);
});
<div class="product__upsell-image">
<img src="{{ all_products[product_one].variants[0].featured_image.src | img_url: 'master' }}" data-src="" alt="">
</div>
<div class="product__upsell-form">
<form class="upsell__form" id="product-upsell" method="post" action="/cart/add" id="form--{{ upsell_prod1.id }}">
<!-- Variant selector -->
<select calss="upsell-variants" name="id">
{% for variant in upsell_prod1.variants %}
<option class="upsell-variants__selector" data-src="{{variant.featured_image.src | img_url: 'master'}}" data-variant="{{ variant.id }}" value="{{ variant.id }}"
{% if variant == current_variant %}selected="selected"{% endif %}
>
{{ variant.title }}{%comment%} - {{ variant.price | money }} {%endcomment%}{% if variant.inventory_quantity <= 0 %}- Sold Out{%endif%}
</option>
{% endfor %}
</select>
<div class="product__upsell-price">{{ all_products[product_one].variants[1].price | money }}</div>
<button type="submit" class="btn upsell-atc single-ajax-cart-btn-upsell" id="add-to-cart-button">Quick Add</button>
</form>
2
Answers
This solution worked for me:
If you want to handle a change in a select element’s value, you probably want to use the $.change() function here. It will attach an ‘change’ event handler to your select element – this way you could just put the URL in the value attribute.