Thursday, July 24, 2008

Javascript - Adding options to select box

Adding options to List Box in client side Javascript

Options to a drop down list box can be added dynamically using client side JavaScript.

function addOption(selectbox,text,value )
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;

Note that each time the 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.Month_list,”January”, “January”);

So this way we can create a drop down list box of all the months by calling the function each time for a month. So with this now you can easily create the list box. But we will add another step to this by using one array of months. So from the array of months we will loop through and add each month to the list box. Here is how to create the array

var month = new Array("January","February","March","April","May","June",

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 < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);

And if you want to clear the options use:

document.drop_list.Month_list.options.length = 0;

No comments: