Shopify: Function to trigger a variant selection change

2.5k views Asked by At

I am trying to add a quantity discount to my shop, but I have some issues. I want to have different variants for a product, and according to the quantity selected, then I add the right variant to the cart. Bascially I manage to do it through the AJAX cart, so the right variant is added to the cart according to the quantity. But now, on the product page, I would like to have the right variant showing with the right price after the quantity has been updated. So after entering the quantity in the quantity box, a function is triggered and updates the selected variant. Something like "onkeyup="myFunction()". Then after reading the quantity box value, choose the right variant and display that variant.

But I cant figure out where the product.selected value is set or how to change it, if it exists as a JSON somewhere, or if this is the right thing to change at all.

I have read that post : Shopify Variants

It confirms that it is possible but I still can't find how.

Thanks for your help.

Ro

1

There are 1 answers

0
RPI On

I found an answer and could fix my issue. In case someone is interested, check the thread here: https://goo.gl/45aGXn

Code as below:

$('#Quantity').keyup(function(){
  if('{{ product.options.first }}' == 'qty'){
      var qty = $('#Quantity').val();                                     
      jQuery.getJSON('/products/' + '{{product.handle}}' + '.js', function (product) {
        for (var i=product.variants.length-1;i>=0;i--){
              if (qty >= parseInt(product.variants[i].title.slice(0,-1))){
               optionSelector.selectVariant(product.variants[i].id);
            break;
              }
           }           
    });    
      }
});