HTML + JavaScript : Change the value of second drop-down list based on the first drop-down list
Source code for 2 drop-down list where the value of the second drop-down list will change based on value in the first drop-down list.
|
![]() |
| First drop-down list selection. |
![]() |
| Second drop-down list value based on first drop-down list. |
<!DOCTYPE html>
<html>
<head>
<title>2 Dropdown Menus Example</title>
</head>
<body>
<select name="state" id="state" onChange="changeState(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">Selangor</option>
<option value="B">Perak</option>
<option value="C">Kedah</option>
</select>
<select name="city" id="city">
<option value="" disabled selected>Select</option>
</select>
</body>
</html>
<script>
var cityList = {
A: ["Langat", "ShahAlam", "Sepang", "Hulu Langat"],
B: ["Ipoh", "Sungai Siput", "Lumut", "Bidor"],
C: ["Alor Setar", "Kulim", "Sungai Petani"]
}
function changeState(value) {
if (value.length == 0) document.getElementById("city").innerHTML = "<option></option>";
else {
var cityChoose = "";
for (city in cityList[value]) {
cityChoose += "<option>" + cityList[value][city] + "</option>";
}
document.getElementById("city").innerHTML = cityChoose;
}
}
</script>


Comments
Post a Comment