Esm1nec,
выбирать для теста 1 , 1 - 1, ...
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
</head>
<body>
<div class="chained-selects">
<select id="select-1">
<option selected>Choose level 1 option</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select id="select-2" disabled>
<option selected>Choose level 2 option</option>
</select>
<select id="select-3" disabled>
<option selected>Choose level 3 option</option>
</select>
</div>
<script>
var options = generateOptions();
document.querySelector('.chained-selects').addEventListener('change', onChange, false);
function onChange(e) {
e.stopPropagation();
var s = e.target;
if (!s.nextElementSibling)
return;
var next = s.nextElementSibling;
if (s.selectedIndex === 0)
deactivateBoxes(next);
else {
var path = [];
for (var p = s; p; p = p.previousElementSibling) {
var selOptNode = p.options[p.selectedIndex];
path.push(selOptNode.value);
}
path.reverse();
var children = path.reduce(
function(o, optName) {
return o[optName];
},
options
);
/*
if (children === null) {
children = fetch(path);
o[...] = children;
}
*/
var values = next.id == "select-3" ? Object.values(children) : [];
children = Object.keys(children);
// Insert children in s.nextChild
for (var q = next.firstElementChild.nextElementSibling; q; q = nextq) {
nextq = q.nextElementSibling;
next.removeChild(q);
}
for (var i = 0; i < children.length; ++i) {
var text = children[i];
var value = values[i] || text;
var optEl = new Option(text, value)
next.appendChild(optEl);
}
next.selectedIndex = 0;
next.disabled = false;
deactivateBoxes(next.nextElementSibling);
}
}
function deactivateBoxes(s) {
while (s) {
s.selectedIndex = 0;
s.disabled = true;
s = s.nextElementSibling;
}
}
function generateOptions() {
return {
'1': {
'1-1': {
'1-1-1 codepen': 'https://codepen.io/',
'1-1-2 google': 'https://www.google.com/'
},
'1-2': {
'1-2-1': null,
'1-2-2': null,
'1-2-3': null,
'1-2-4': null,
},
'1-3': {
'1-3-1': null,
'1-3-2': null,
'1-3-3': null,
'1-3-4': null,
'1-3-5': null,
}
},
'2': {
'2-1': {
'2-1-1': null,
'2-1-2': null
},
'2-2': {
'2-2-1': null,
'2-2-2': null,
'2-2-3': null,
'2-2-4': null,
},
'2-3': {
'2-3-1': null,
'2-3-2': null,
'2-3-3': null,
'2-3-4': null,
'2-3-5': null,
}
},
'3': {
'3-1': {
'3-1-1': null,
'3-1-2': null
},
'3-2': {
'3-2-1': null,
'3-2-2': null,
'3-2-3': null,
'3-2-4': null,
},
'3-3': {
'3-3-1': null,
'3-3-2': null,
'3-3-3': null,
'3-3-4': null,
'3-3-5': null,
}
}
};
}
document.querySelector("#select-3").addEventListener("change", function() {
if(this.value.startsWith("https") ) window.location = this.value;
})
</script>
</body>
</html>
|