I’m trying to add css to product options to provide the user with a visual indication of which options are not available (sold out). This works when a product only has one set of option values, however my product has two ("date", and "time"). I have this working most of the way, however the available "Time" options are not updated when I switch between dates. Any help here would be hugely appreciated.
Inside my product-form.liquid file I have the following code to add a class to sold out options. Perhaps I need some js?
In case it’s helpful, I’m using the Prestige theme and the page is here: https://neetfield.co.uk/pizza
{%- if option.name == "Time" and product.selected_or_first_available_variant.option1 == product.variants[forloop.index0].option1 -%}
{%- if product.variants[forloop.index0].available -%}
{%- assign opt_sold = false -%}
{%- else -%}
{%- assign opt_sold = true -%}
{%- endif -%}
{%- else -%}
{%- assign opt_sold = false -%}
{%- endif -%}
And then this is used to add a class to sold out options {% if opt_sold %}opt-sold-out{% endif %}
This is a screenshot of where I got to (now disabled on the live site until I haved it working when switching between dates):
2
Answers
First page render (Liquid)
For the initial page load you can use something like this:
This snippet iterates over all product variants where
option1
equals theoption1
value of the currently selected variant (e.g. "Saturday 4th June"). For each variant we’ll check if its available and push it to theavailable_timeslots
array.Make sure to place this snippet before iterating over all product options.
Finally, use this array to check if an option value is available:
value
basically is a value ofoption.values
. I’m sure you’ll find this somewhere in your product-form 🙂After user interaction (JavaScript)
Since Liquid is a server-side rendered template language, you can only achieve this by updating the option input elements on variant change via JavaScript on the client-side. The Shopify Prestige theme has a useful CustomEvent for this scenario:
variant:changed
An example of the implementation would look like this:
Keep in mind that you are not really disabling the input. It’s just visually indicating that it’s disabled. If that’s not a problem for you, just ignore this comment.
Note that this does not handle the following scenario:
I’m guessing that the decision which date to chose always comes first so this should not be an important scenario to worry about.
Approach for products with a single option
This case is pretty easy and does not require any JavaScript since each option value maps to exactly one variant. The way to go here would be to get that variant and check if it’s available: