Plain JS Cascading selects of unknown depth
Doing this in React would be easier,. But for a plain JS solution the below might be what your after.
Basically all I'm doing is using recursion to create the components, and attach the events.
const selObject = {
"-- Select Item --": {
"Clothes": {
"-- Select brands --": {
"Levis": {
"-- Select product --": {
"Jeans": {
"-- Select size --": [
"38",
"39",
"40"
]
},
"Jackets": {
"-- Select size --": [
"41",
"42",
"43"
]
}
}
}, // end Levis
"Gucci": {
"-- Select product --": {
"Shoes": {
"-- Select size --": [
"45",
"50",
"55"
]
},
"Dresses": {
"-- Select size --": [
"8",
"9",
"10"
]
}
}
} // end Gucci
} // end brands
}, // End clothes
"Gadgets": {
"-- Select brands --": {
"LG": {
"-- Select product --": {
"TVs": {
"-- Select size --": [
"38",
"39",
"40"
]
},
"Phones": {
"-- Select size --": [
"8",
"9",
"10"
]
}
}
}, // end Levis
"Apple": {
"-- Select product --": {
"Macbooks": {
"-- Select size --": [
"15",
"17",
"21"
]
},
"iPhones": {
"-- Select size --": [
"8",
"9",
"10"
]
}
}
} // end Apple
} // end brands
} // end Gadgets
} // end items
} // end
function fillDropdown(target, obj) {
const sel = document.createElement("select");
const sub = document.createElement("div");
if (typeof obj !== "object") {
sub.innerHTML = "<p>Thank you for your selection</p>";
target.appendChild(sub);
return;
}
target.appendChild(sel);
target.appendChild(sub);
const [title, value] = Object.entries(obj)[0];
//add our title option
const option1 = document.createElement("option");
option1.innerText = title;
sel.appendChild(option1);
//now add the sub items
const items = Object.entries(value);
items.forEach(([k, v]) => {
const option = document.createElement('option');
option.innerText = k;
sel.appendChild(option);
});
sel.addEventListener("change", () => {
sub.innerHTML = "";
if (sel.selectedIndex > 0) {
const i = items[sel.selectedIndex - 1];
fillDropdown(sub, i[1]);
}
});
}
window.onload = function() {
//createSel(selObject);
fillDropdown(
document.querySelector('#selContainer'),
selObject
);
}
select {
display: block;
width: 100%;
padding: 10px;
}
<form name="myform" id="myForm">
<div id="selContainer">
</div>
</form>