Forked from zakhardage/Much much simpler option selector for Shopify
Last active
October 5, 2022 19:33
-
-
Save husseyexplores/54a1c1a5e2766702cb4ce93df3da55cf to your computer and use it in GitHub Desktop.
Much simpler version of Shopify's option_selection.js for separating product options into their own dropdown menus.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <form action="/cart/add" method="post" enctype="multipart/form-data" class="product-form" id="AddToCartForm"> | |
| {% unless product.has_only_default_variant %} | |
| {% for option in product.options_with_values %} | |
| <label {% if option.name == 'default' %}class="label--hidden" {% endif %}for="SingleOptionSelector-{{ forloop.index }}">{{ option.name }}</label> | |
| <select id="SingleOptionSelector-{{ forloop.index }}" onchange="updateVariant();"> | |
| {% for value in option.values %} | |
| <option value="{{ value | escape }}"{% if option.selected_value == value %} selected="selected"{% endif %}>{{ value }}</option> | |
| {% endfor %} | |
| </select> | |
| {% endfor %} | |
| {% endunless %} | |
| <input type="hidden" name="id" id="selected-variant" value="{{ product.variants.first.id }}" /> | |
| <button type="submit" name="add" id="AddToCartBtn">Add to Cart</button> | |
| </form> | |
| {% unless product.has_only_default_variant %} | |
| <script> | |
| var selectors = { | |
| selectedVariant: document.querySelector("#selected-variant"), | |
| productPrice: document.querySelector("#ProductPrice-{{ section.id }}"), | |
| } | |
| function updateVariant() { | |
| var id = ""; | |
| var price = ""; | |
| {% for option in product.options_with_values %} | |
| var option{{ forloop.index }} = document.querySelector("#SingleOptionSelector-{{ forloop.index }}").value; | |
| {% endfor %} | |
| {% for variant in product.variants %} | |
| if({% for option in variant.options %} option{{ forloop.index }} == "{{ option }}" {% unless forloop.last %} && {% endunless %}{% endfor %}) { | |
| id = {{ variant.id }}; | |
| price = "{{ variant.price | money }}"; | |
| } | |
| {% endfor %} | |
| if(id != "") { | |
| selectors.selectedVariant.value = id; | |
| selectors.productPrice.innerHTML = price; | |
| } else { | |
| selectors.selectedVariant.value = ""; | |
| selectors.productPrice.innerHTML = "Unavailable"; | |
| } | |
| } | |
| </script> | |
| {% endunless %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment