Javascript populating options for a select tag

index.html

<!DOCTYPE html>
<html>
<head>
<title>Unit Converter</title>
<script type="text/javascript" src="uselector.js"></script>
</head>
</body>
    <select style="width:200px;"  id="uc_selector_main" onchange="unitMenuChange(this);">
      <option value="0">Select</option>
      <option value="Area">Area</option>
      <option value="Length">Length</option>
    </select>
    <br>
    <select style="width:200px;"  id="uc_selector">
    <option value="0">Select a unit</option>
    </select>
</body>
</html>

uselector.js

var unitLists = new Array(2) 
unitLists["0"] = ["Select"]; 
unitLists["Area"] = 
["Square millimeters",
"Square centimeters",
"Square meters",
"Square kilometers",
"Square miles",
"Hectares",
"Acres",
"Square inches",
"Square feet",
"Square yards"];

 unitLists["Length"] = 
 ["Nanometers",
"Micrometers",
"Millimeters",
"Centimeters",
"Meters",
"Kilometers",
"Miles",
"Nautical Miles",
"Inches",
"Feet",
"Yards"];


 /* unitMenuChange() is called from the onchange event of a select element. 
 * param selectObj - the select object which fired the on change event. 
 */ 
function unitMenuChange(selectObj) { 
	var idx = selectObj.selectedIndex;
	var which = selectObj.options[idx].value;
	uList = unitLists[which];
	var uc_selector = document.getElementById("uc_selector");

	while (uc_selector.options.length > 0) { 
		uc_selector.remove(0); 
	}
	var newOption;
	// create and add new options 
	for (var i=0; i<uList.length; i++) {
		newOption = document.createElement("option"); 
		newOption.value = uList[i];  
		newOption.text=uList[i];
		try { 
			uc_selector.add(newOption); 
			} 
		catch (e) { 
			uc_selector.appendChild(newOption);
			} 
	}
 }

demo

Search within Codexpedia

Custom Search

Search the entire web

Custom Search