FREE tutorial,solution,RSS Feeds on Operating Systems, Programming, Web Development, Applications, Databases, Networking, Hardware, Security, SEO Free Expertsforge Membership
Join us as Moderator
Submit Article to Expertsforge.com Submit Article My Expertsforge
 
RSS Feeds, Help Help RSS Feeds
bannertop
 

JavaScript Tutorial: Adding Options dynamically to the list box using Javascript

jawahar
1/10/2007 1:22:54 PM, Views: 1849
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 values

We 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>
Next Steps:
Add this Tutorial to:
Blink Blink del.icio.ous Del.icio.us Digg Digg
Fark Fark Furl Furl Google Google
Reddit Reddit Simpy Simpy Spurl Spurl
Technorati Technorati Windows Live Win Live Yahoo Yahoo
Rate Me!
Avg Visitor Rating: Average Visitor Rating is 3.5 out of 5
Number of Ratings : 2 Votes
Rate:
Send Private MessageSend Message
Signup / Login To View the Solution or Provide Comments
Post Comment/Solution
Comment:*
        (Link Rules) 
  Use : [bold] for <b>; [/bold] for </b>; [italic] for <i>; [/italic] for </i>; [code] & [/code] for code
 
Categories
Options
JavaScript RSS Feed
Most Popular Tutorial
Most Popular Solution
Top Rated
Top Contributors
Yearly
Overall
 
1. jawahar (300)
bnrtop