Dynamically filled Select Element

Example 1

Dynamically fill Select Element based on Country Selected.

Code:

<script>
//initialize some variables to use below
	var regions;
	var canReg = ["Alberta", "British Columbia", "Saskatchewan", "Manitoba",
			"Ontario", "Quebec", "Nova Scotia", "New Brunswick", "Newfoundland Labrador",
			"Yukon", "Nunavit", "NWT"];
	//american states are not complete, but you get the idea!
	var amReg = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorodo", "Connecticut"];
	var country;
	
	//called on body load, this function initially sets up the dropdown of regions 
	//based on the default being Canada
	function init(){
		country = "Canada";
		regions = canReg.slice();//the slice function copies the array into another array
		fillselect('CA');
	}
	//called when the country changes, this function clears the current contents of the 
	//regions list, and then calls fillselect to refill it
	function updateList(){
		var element = document.getElementById("Region");
		var i;
		//iterate through the array, and remove each element
		//we remove from the end so that we don't mess up the array
		for(i = element.options.length - 1 ; i >= 0 ; i--)
		{
			element.remove(i);
		}	
		//fillselect is called with the value of the selected item
		fillselect(document.getElementById("Country").value);
	}
	//fills the region dropdown list based on the currently selected list
	function fillselect(countryCode){
		var el = document.getElementById("Region");
		if(countryCode === "CA"){
			regions = canReg.slice();
		
		}else{
			regions = amReg.slice();
		}
		for(var i=0; i<regions.length; i++){
			//we have to create an option element
			var option = document.createElement("option");
			//we then set the value of the option to the text in the array
			//and then assign this value to the innerHTML (which is the text that
			//is shown to the user)
			option.innerHTML = option.value = regions[i];
			//we append this option to the select element
			el.appendChild(option);
		}
	}
</script>

Output: