How to get currently selected variant using Javascript/jQuery??

Solved
Highlighted
Tourist
3 0 0

Hi. Been banging my head against the wall trying to figure this out.

Is there a way I can get selected variant id via jQuery onLoad? Essentially what {{ product.selected_or_first_available_variant }} would return in Liquid. I need to get via js.

 

I've able to get the data when the customer selects a diff variant. But not the initial one that is loaded.

 

I need to display a warning message on certain variants. I want to check if the selected variant.id is on the bad list, then add the warning dynamically to product description.

 

Is there a way I can get selected variant id via jQuery onLoad?

 

 

0 Likes
Highlighted
Shopify Partner
2294 116 353

This is an accepted solution.

Quick way if using deep linking is to just get the ID from the variant parameter ( i.e. /productname?variant=12345678901234)

But obviously that will fail on parameterless urls

 

Otherwise just get the id from the selected html inputs though watch out for any code that needs to run first on selectors that could change things.

Or you could find the selector_options logic in the themes javascript and set it there

Or find the initialization code and expose it so you can access it.

Or <script> window.shop.loaded_variant = {{ product.selected_variant.id }};</script>

Problem Solved? ✔️Accept and ? Like the solution so you can help others.
Buy me a coffee ☕ paypal.me/paulnewton or donate to eff.org
Confused? Busy? Buy a custom solution paull.newton+shopifyforum@gmail.com
1 Like
Highlighted
Tourist
3 0 0

ya, I've opted to get the info based on selected html inputs for the form. thanks for the quick response. 

0 Likes