This is a simple script using JS to display cascading multi level select form. We are storing all these data in the form of JS object instead of Database.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
var locationObject = {
"AP": {
"East Godavari": {
"Sakhinetipalli": ["Mori", "Antharvedi", "SVP", "KDP"],
"Malkipuram": ["Lakkavaram", "RR Lanka"],
"Razole": ["Merakapalem", "Kunavaram", "Gudapalli"]
},
"West Godavari": {
"Narsapuram": ["V1", "V2", "V3"],
"Bhimavaram": ["V4", "V5", "V6"]
}
},
"TS": {
"Nizambad": {
"Nizam Mandal": ["f1", "f2", "f3"],
"A Mandal": ["r1", "r2"]
},
"Hyderabad": {
"Rangareddy": ["t7", "t8", "t9"],
"Kompalli": ["g1", "g2"]
}
}
}
window.onload = function() {
var stateSel = document.getElementById("subject");
var distSel = document.getElementById("topic");
var mandalSel = document.getElementById("chapter");
var locationSel = document.getElementById("lesson");
for (var x in locationObject) {
stateSel.options[stateSel.options.length] = new Option(x, x);
}
stateSel.onchange = function() {
//empty Chapters- and Topics- dropdowns
locationSel.length = 1;
mandalSel.length = 1;
distSel.length = 1;
//display correct values
for (var y in locationObject[this.value]) {
distSel.options[distSel.options.length] = new Option(y, y);
}
}
distSel.onchange = function() {
//empty Chapters dropdown
locationSel.length = 1;
mandalSel.length = 1;
//display correct values
for (var z in locationObject[stateSel.value][this.value]) {
mandalSel.options[mandalSel.options.length] = new Option(z, z);
}
}
mandalSel.onchange = function() {
//empty Chapters dropdown
locationSel.length = 1;
//display correct values
var w = locationObject[stateSel.value][distSel.value][this.value];
for (var i = 0; i < w.length; i++) {
locationSel.options[locationSel.options.length] = new Option(w[i], w[i]);
}
}
}
</script>
</head>
<body>
<h1>Cascading Dropdown Example</h1>
<form name="form1" id="form1" action="/action_page.php">
STATE: <select name="subject" id="subject">
<option value="" selected="selected">Select State</option>
</select>
<br><br>
DISTRICT: <select name="topic" id="topic">
<option value="" selected="selected">Please select State first</option>
</select>
<br><br>
MANDAL: <select name="chapter" id="chapter">
<option value="" selected="selected">Please select District first</option>
</select>
<br><br>
LOCATION: <select name="lesson" id="lesson">
<option value="" selected="selected">Please select Mandal first</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Thank You.
Happy Coding...
ConversionConversion EmoticonEmoticon