Search Search

#1 worldwide
FREE Coding Lessons

since 1996
   THE BEST WAY to learn ASP & Asp.net!
Advertise Here!
click for details
Credits Host:
DiscountASP.net
Server Admin:
The "Team"
Contact Info.
Charles M. Carroll

my Blog
[prev. Lesson]  Validation Resources
     [next Lesson]  Dynamic ListBox Online Examples

Dynamic Client Dependent Lists/JScript

Sometimes you need a Listbox that changes in response to a value of another listbox. The most effective way is to use client-side Jscript as illustrated below:

   filename=/learn/test/listdynamic.asp

<Test Script Below>


<HTML>
<HEAD><TITLE>Dynamic Select Lists</Title></Head>
<BODY OnLoad="BuildContacts(0);">
<FORM Name="myForm">
Salesperson:
<SELECT Name="SalesNames" OnChange="BuildContacts(this.selectedIndex);">
   <OPTION Value="Jeff">Jeff
   <OPTION Value="Charles">Charles
   <OPTION Value="Rick">Rick
   <OPTION Value="Kevin">Kevin
</Select>
<BR><BR>
Contacts:
<!-- We want to define at least one option so that the select tag is created
     with the correct dimensions-->
<SELECT Name="SalesContacts">
   <OPTION Value="">--------
</Select>
</Form>
</Body>
</Html>

<SCRIPT Language="JavaScript"><!--

//Build arrays for each person's contacts
Contacts=new Array(4);
Contacts[0]=new Array(3);
Contacts[1]=new Array(2);
Contacts[2]=new Array(5);
Contacts[3]=new Array(4);

//Charles
Contacts[0][0]="Bill";
Contacts[0][1]="Bob";
Contacts[0][2]="Chuck";

//Jeff
Contacts[1][0]="Vern";
Contacts[1][1]="Matt";

//Rick
Contacts[2][0]="Diana";
Contacts[2][1]="Dave";
Contacts[2][2]="Todd";
Contacts[2][3]="Sherry";
Contacts[2][4]="Sharon";

//Kevin
Contacts[3][0]="Brian";
Contacts[3][1]="Trisha";
Contacts[3][2]="Greg";
Contacts[3][3]="Troy";

//Call this to build the Contact list for the specified Salesperson
function BuildContacts(num)
{
   //Select the first Contact
   document.myForm.SalesContacts.selectedIndex=0;
   
   //For every contact in the array for this person, add a new option
   for(ctr=0;ctr<Contacts[num].length;ctr++)
   {
      document.myForm.SalesContacts.options[ctr]=new Option(Contacts[num][ctr],Contacts[num][ctr]);
   }
   //Set the length of the select list
   document.myForm.SalesContacts.length=Contacts[num].length;
}
//--></Script>

Send Us a Holiday Gift!. Charles celebrates Christmas, Jewish holidays, Kwanza, Chinese New Year, Japanese Holidays, Secretary Day, High Muslim Holy Days, Pagan & Wicca holidays, and many more! - send a gift any HOLIDAY. 2004 gift gallery & 2005 gift gallery