Tip: Dynamically Adding Items to Select Field with JavaScript

The document.create method of JavaScript allows you to create elements. The example blow shows you how to use document.create element to dynamically add items to a select field. You can also view a demo of this code here

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamically Adding Items to Select Field with JavaScript</title>
<script language="javascript"> 
	function addItem(){
		var e1=document.getElementById('item');
		var e2=document.getElementById('items');
		var o=document.createElement('option');
		o.value=e1.value;
		o.text=e1.value;
		e2.options.add(o);
	}
 </script>
</head>

<body>
	<input type="text" name="item" id="item" />
    <input type="button" value="Add to List" onclick="addItem()" /><br />
	<select id="items" name="items">

    </select>
</body>
</html>

 

More Javascript tips