| |
|
Adding options to List Box in client side Javascript |
Options to a drop down list box can be added dynamically using client side JavaScript. We will discuss a simple way of adding options to a list. The process of adding can be controlled based on different condition required. Depending on conditions options can be removed also.
Here we will take care that the options are added on the page load , so by default the list box is pre populated when the page is displayed. You can see the demo at the end of this page. The main function creates a new OPTION object and assigns values and text part of the option. Here is the function which collects the list box name, value and text as inputs and then adds the option to the list box. Here is the function
function addOption(selectbox,text,value )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
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", "July","August","September","October","November","December");
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]);
}
You can see with this array we will able to populate the drop down list box of months. Here is the simple code for html body tag and the form with drop down list
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000" onLoad="addOption_list()";>
<FORM name="drop_list" action="yourpage.php" method="POST" >
<SELECT NAME="Month_list">
<Option value="" >Month list</option>
</SELECT>
</form>
</body>
| |
| Subscribe |
|
Submit your email address and receive
article and product notifications. Your email is safe with us.
|
|
|
|
| JavaScript Tutorials |
| Popular Tutorials |
|
| Drop down list |
| Timer function |
| JavaScript Tutorials |
|
| String |
| Array |
| Date & Time |
| Form Validation |
| Event Handling |
| Math Functions |
| Loops & structure |
| JavaScript Forum |
| Subscribe |
|
Submit your email address and receive
article and product notifications. Your email is safe with us.
|
|
|
|