Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you populate one listbox based on what is selected in a second

Status
Not open for further replies.

bongmarley

Programmer
Oct 21, 2002
74
CA
I have two listboxes one for sex and one for name.When male is selected from listbox i want the name listbox only to be populated with Male names and vice versa. How do I go about this using javascript
 
The following code should accomplish what you want. I've put comments in the Javascript code to explain what i'm doing.

You can take the following code and place it in a blank .html file. It should work fine.

<html>
<head>
<title>Untitled</title>
</head>
<script>
//arrays to contain the names
var males = new Array(&quot;Sundin&quot;,&quot;Mogilny&quot;,&quot;Belfour&quot;)
var females = new Array(&quot;Faith&quot;,&quot;Shania&quot;,&quot;LeAnn&quot;,&quot;Womack&quot;)

function Populate(name)
{
//if the male option was selected
if(name==&quot;m&quot;)
{
//make the menu elements in the name menu equal to the number of names in the male array
document.all[&quot;nameList&quot;].options.length=males.length
for(var x=0;x<males.length;x++){
//the text and value of each element will be the name that is in the array
document.all[&quot;nameList&quot;][x].text = males[x]
document.all[&quot;nameList&quot;][x].value = males[x]
}
}
if(name==&quot;f&quot;)
{
//make the menu elements in the name menu equal to the number of names in the male array
document.all[&quot;nameList&quot;].options.length=females.length
for(var x=0;x<females.length;x++){
//the text and value of each element will be the name that is in the array
document.all[&quot;nameList&quot;][x].text = females[x]
document.all[&quot;nameList&quot;][x].value = females[x]
}
}
if(name==&quot;x&quot;)
{
document.all[&quot;nameList&quot;].options.length=1
document.all[&quot;nameList&quot;][0].text = &quot;Choose&quot;;
document.all[&quot;nameList&quot;][0].value = &quot;Choose&quot;;
}

}
</script>
<body>
<select name=&quot;gender&quot; onChange=&quot;Populate(this.value)&quot;>
<option value=&quot;x&quot;>Select
<option value=&quot;m&quot;>Male
<option value=&quot;f&quot;>Female
</select>

<select name=&quot;nameList&quot;>
<option value=&quot;x&quot;>Choose
</select>
</body>
</html>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top