The following tutorial with code will guide you how to add options/items to the list box dynamically using javascript
Method 1:First, we will create a function that will create a new OPTION object and assigns values and text part of the option. This function collects the list box name, value and text as inputs and then adds the option to the list box. The function goes like this,
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
When this function is called, it adds a new option to the list box. So we can add one option by calling the function once. Like this.
addOption(document.drop_list.Name_list,"John", "John");
Consider that we have many options, calling the above function 'n' times is not easy. So, we will move on to the next method.
Method 2: Populating the list box from an array of valuesWe will now populate/add items to the list box from an array of values by looping through and add each values to the list box. Here is how to create the array
var namelist = new Array("John","Jack","Marlin","George");
So now once our array is ready with data, we will loop through the array by using for loop and then call the addOption function using the data of the array. Here is the code.
for (var i=0; i < namelist.length;++i)
{
addOption(document.drop_list.Name_list, namelist[i], namelist[i]);
}
With this array we will able to populate the drop down list box of names. Here is the simple code for html body tag and the form with drop down list
<body onLoad="addOption_list()";>
<FORM name="drop_list" action="yourpage.asp" method="POST">
<SELECT NAME="Name_list">
<Option value="" >Name list</option>
</SELECT>
</form>
</body>