Reputation: 543
I am building a custom "subscription builder" where customers select options, proceed to the next step and at the end click checkout; their options reflected in the variant selected.
The way Im going about this is by hiding shopify's selectors and setting them manually using $().val(); This accurately changes the selectors (checking in inspector), but Shopify does not recognize these changes for some reason and so the product added to the cart is the default. I am obviously missing something - is this even possible?
[Code Redacted for uselessness]
Thank you!
Upvotes: 0
Views: 3647
Reputation: 543
Basically,
Shopify's option_selection.js controls this and has a "Product" and "OptionSelector" object.
OptionSelector has a function selectVariant(id, selector) that will properly set it given you have the full variant identifier.
In your product_form.liquid you will see a place that does new OptionSelector(args). You simply save what it returns, i.e.
selector = new OptionSelector(...);
then you can do
selector.selectVariant("123456789", selector);
This will properly set the variant for the checkout button. You can then either hide the 'shopify' selectors with css / js or keep them or modify the option_selection.js code yourself by downloading from here.
Furthermore, I've discovered more useful things one can do:
selector.selectors[index].element.value {get; set;} //much cleaner method of accessing selector elements
selector.product.getVariant(selector.selectedValues()).id // gets the variant id for you so you do not need to hardcore them in
EDIT: Dave has kindly pointed out that
$(element).val(newValue).trigger('change');
Would have done what I wanted, but points out (and I agree) that using OptionSelector is more of a robust method.
Upvotes: 2