Created
July 7, 2022 08:39
-
-
Save jimmijazz/2413f09f16f6e20d6d2b2d74f12ebfeb to your computer and use it in GitHub Desktop.
Filtering variant options
This file contains 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
/* MTBD Product filtering solution * | |
This could all be done in liquid as well | |
Add a product-options id to the fieldset | |
*/ | |
var options = [[], [], [], []]; | |
var optionsFieldSet = document.getElementById("product-options"); | |
var fieldSetInputs = optionsFieldSet.getElementsByTagName("input"); | |
fieldSetInputs.forEach((input) => { | |
let optionName = input["defaultValue"]; | |
let variantOptions = optionName.split(" - "); | |
options.forEach((option, index) => { | |
if (!option.includes(variantOptions[index])) { | |
options[index].push(variantOptions[index]); | |
} | |
}); | |
}); | |
for (let key in options) { | |
options[key].unshift("All"); // Add an all option to unfilter | |
let inputHTMLString = `<select style="width:20%;" onchange="applyFilter()" class="filter-option facet-filters__sort select__select caption-large">`; | |
let alreadyAdded = []; | |
options[key].forEach((option) => { | |
if (!alreadyAdded.includes(option)) { | |
inputHTMLString += `<option value="${option}">${option}</option>`; | |
alreadyAdded.push(option); | |
} | |
}); | |
inputHTMLString += "</select>"; | |
optionsFieldSet.innerHTML = inputHTMLString + optionsFieldSet.innerHTML; | |
} | |
// Listen for filter changes | |
function applyFilter() { | |
let filterSelected = []; | |
// Get filter values | |
var filterValues = document.getElementsByClassName("filter-option"); | |
filterValues.forEach((filterValue) => { | |
filterSelected.push(filterValue.options[filterValue.selectedIndex].value); | |
}); | |
filterSelected.reverse(); | |
// Loop variants | |
fieldSetInputs.forEach((variant) => { | |
let show = true; | |
let variantOptions = variant.value.split("-"); | |
let variantMatch = []; | |
variantOptions.forEach((variantOption, index) => { | |
if (filterSelected[index] === "All") { | |
variantMatch.push(true) | |
} else if (filterSelected[index].replace(/\s+/g, "") == variantOption.replace(/\s+/g, "")) { | |
variantMatch.push(true) | |
} else { | |
variantMatch.push(false) | |
}; | |
if (variantMatch.includes(false)) { | |
show = false; | |
}; | |
}); | |
if (!show) { | |
variant.style.display = "none"; // Hide variant input | |
document.querySelector(`label[for='${variant.id}']`).style.display ="none"; // Hide label | |
} else { | |
variant.style.display = "block"; // Hide variant input | |
document.querySelector(`label[for='${variant.id}']`).style.display ="block"; // Hide label | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment