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
2427 124 381

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
2 Likes
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
Highlighted

Thanks @PaulNewton , I did something similar.

I actually didn't want the URL to have parameters, however, inside the theme there was a function already setting the URL parameters. s

So instead of showing it up in the URL I just added it to a local object:

window.variant = variant

And was able to use wherever I wanted.

◦ Problem Solved? ✔️ Please click on Accept as Solution and like.
◦ Needing urgent help? I'm available for hire, same day response guaranteed: diego.boarutto.fortes@gmail.com
◦ My app free for limited time: Add a navigation styled like Instagram Stories to your website!
0 Likes
Highlighted
Shopify Partner
2427 124 381

@diego_ezfy wrote:

...
So instead of showing it up in the URL I just added it to a local object:

window.variant = variant

And was able to use wherever I wanted.


You want to namespace that ,  avoid setting common property names directly on the window object.

This avoids habitual problems across themes(especially collection pages) and with apps that also chose to not namespace properties.

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