Skip to content

Instantly share code, notes, and snippets.

@JamieS
Forked from carolineschnapp/gist:1083007
Created July 14, 2011 21:49
Show Gist options
  • Save JamieS/1083549 to your computer and use it in GitHub Desktop.
Save JamieS/1083549 to your computer and use it in GitHub Desktop.
Linked options helper methods for Shopify. See this: http://wiki.shopify.com/Linked_Options
<script>
// (c) Copyright 2011 Caroline Schnapp. All Rights Reserved. Contact: [email protected]
// See http://wiki.shopify.com/Linked_Options
Shopify.optionsMap = {};
Shopify.updateOptionsInSelector = function(selectorIndex) {
var key = jQuery('.single-option-selector:eq(0)').val();
if (selectorIndex === 2) {
key += ' / ' + jQuery('.single-option-selector:eq(1)').val();
}
var selector = jQuery('.single-option-selector:eq(' + selectorIndex + ')');
var initialValue = selector.val();
selector.empty();
var availableOptions = Shopify.optionsMap[key];
for (var i=0; i<availableOptions.length; i++) {
var option = availableOptions[i];
var newOption = jQuery("<option></option>").val(option).html(option);
selector.append(newOption);
}
if (jQuery.inArray(initialValue, availableOptions) !== -1) {
selector.val(initialValue);
}
selector.trigger('change');
};
Shopify.linkOptionSelectors = function(product) {
// If we have only one option, we have nothing to do.
if (product.options.length === 1) return;
// Building our mapping object.
for (var i=0; i<product.variants.length; i++) {
var variant = product.variants[i];
if (variant.available) {
var key = variant.option1;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option2);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
if (product.options.length === 3) {
var key = variant.option1 + ' / ' + variant.option2;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option3);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
}
}
// Update options right away.
Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
// When there is an update in the first dropdown.
jQuery(".single-option-selector:eq(0)").change(function() {
Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
// When there is an update in the second dropdown.
jQuery(".single-option-selector:eq(1)").change(function() {
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment