Может пригодится кому-то
document.addEventListener("DOMContentLoaded", function() {
function generateOptions() {
return {
"AUDI": {
"80": {
url: "p80.html"
},
"100": {
url: "audi100.html"
},
"url": "AUDI.html"
},
"BMW": {
"3 series": {
url: "p3.html"
},
"5 series": {
url: "p5.html"
},
"url": "BMW.html"
},
"url": "All.html"
};
}
const elem = document.querySelector(".chained-selects");
const selects = Array.from(elem.querySelectorAll("select"));
const getOptions = (obj, path = []) => Object.keys(path.reduce((obj, key) => obj[key], obj)).filter(key => key !== "url");
const createOptions = (target, options) => target.append(...options.map(i => new Option(i, i)));
let options = getOptions(generateOptions());
let target = selects[0];
createOptions(target, options);
const change = ({
target
}) => {
let disabled = false,
path = [],
last;
for (let select of selects) {
let value = select.value;
select.disabled = disabled;
if (disabled) select.options.length = 1;
if (target === select) {
last = true;
} else if (!disabled && last) {
select.options.length = 1;
let options = getOptions(generateOptions(), path);
createOptions(select, options);
};
if (select.selectedIndex === 0) disabled = true;
else path.push(value);
}
}
elem.addEventListener("change", change);
elem.querySelector("button").addEventListener("click", () => {
let obj = generateOptions();
for (let {
value
} of selects) {
if (value in obj) obj = obj[value];
else {
if ("url" in obj) break;
value = Object.keys(obj)[0];
obj = obj[value];
}
}
location.href = obj.url
});
})