Javascript: Populate Select box OnChange with JS array/object

This article show how to populate one select box by selecting option of another select box/list. We will use a Javascript object. Each key of the object contains array as value.

A first select box is populated with the Javascript object’s keys. Then when the value from the first select box is selected then based on that value, the second select box is populated.

The below JS object contains names of zones and districts. There are different districts in a single zone. So, in the below JS object, each zone is the key of the object and the district array is the value of the zones.


var zoneDistrict = {
		"Mechi": ["Jhapa", "Illam", "Panchthar", "Taplejung"],
		"Koshi": ["Sunsari", "Morang", "Bhojpur", "Dhankuta", "Tehrathum", "Sankhuwasabha"],
		"Sagarmatha": ["Siraha", "Saptari", "Udayapur", "Khotang", "Okhaldhunga", "Solukhumbu"]
	}

populateZone() function is called on window load. This function populates the first select box using the keys of zoneDistrict object.

populateDistrict(zone) function is called when any value of the first select box is selected. The name of the zone is passed to the function. Based on the zone name passed, the district array value is selected from zoneDistrict object and the second select box is populated.

Here is the full code:


<html>
	<head>
		<title>Form</title>
		
		<script type="text/javascript">
			var zoneDistrict = {
				"Mechi": ["Jhapa", "Illam", "Panchthar", "Taplejung"],
				"Koshi": ["Sunsari", "Morang", "Bhojpur", "Dhankuta", "Tehrathum", "Sankhuwasabha"],
				"Sagarmatha": ["Siraha", "Saptari", "Udayapur", "Khotang", "Okhaldhunga", "Solukhumbu"]
			}
			
			window.onload = function() {	
				populateZone();
			};
			
			function populateZone() {		
				var zones = "<option>Please Select</option>";
				var data = Object.keys(zoneDistrict); // get keys from zoneDistrict object
				for (i=0; i < data.length; i++) {
					zones += "<option>" + data[i] + "</option>";
				}
				document.getElementById("zone").innerHTML = zones;
			}
				
			function populateDistrict(zone) {	
				var districts = "<option>Please Select</option>";
				var data = zoneDistrict[zone];
				for (i=0; i < data.length; i++) {
					districts += "<option>" + data[i] + "</option>";
				}
				document.getElementById("district").innerHTML = districts;
			}
		</script>	
	</head>
	<body>
		<form>
			<p>
				<select id="zone" onchange="populateDistrict(this.value)">
					<option>Please Select</option>
				</select>
			</p>
			<p>
				<select id="district">
					<option>Please Select</option>
				</select>
			</p>
		</form>
	</body>
</html>		

Hope this helps. Thanks.