faqts : Computers : Programming : Languages : Asp : ASP/VBScript : Common Problems : forms and user input

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

52 of 68 people (76%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I set up the options of one select based on the selection of another within the same .asp page?

Oct 16th, 2000 10:00
Jim Allen, unknown unknown, Paul Perrick


You can do this with some client-side script;
E.g.
<SCRIPT Language="VBScript">
<!-- Define an array corresponding to each item in the first select 
box. Each row in the array is a possible selection for the second list 
box.

Dim arrNotMonkeys(1,1)
  arrNotMonkeys(0,0) = "value1"
  arrNotMonkeys(1,0) = "cat"
  arrNotMonkeys(0,1) = "value2"
  arrNotMonkeys(1,1) = "dog"

Dim arrMonkeys(1,2)
  arrMonkeys(0,0) = "value1"
  arrMonkeys(1,0) = "orang-utan"
  arrMonkeys(0,1) = "value2"
  arrMonkeys(1,1) = "chimpanzee"
  arrMonkeys(0,2) = "value3"
  arrMonkeys(1,2) = "gorilla"

<!- When an option is selected in the first select box this sub is 
called; it decides which is the appropriate array -->
Sub firstSelect_OnChange
  Dim firstSelected
  firstSelected = document.formName.firstSelect.Value

  If firstSelect = "NotPrimates" Then
    PopulateHow arrNotMonkeys, 1
  ElseIf firstSelect = "Primates" Then
    PopulateHow arrMonkeys, 2
  End If
End Sub

<!-- This procedure churns thru the appropriate array, dynamically 
populating the second select box. Setting the length of a select box to 
zero will clear out everything there, starting us with a 'blank 
slate'. -->
Sub PopulateHow(arrOptions, intListLength)
  Dim i, objOption

  document.formName.secondSelect.length = 0

  For i=0 to intListLength
    Set objOption = document.CreateElement("OPTION")
    objOption.Value = arrOptions(0, i)
    objOption.Text = arrOptions(1, i)
    document.formName.secondSelect.add objOption
    Set objOption = Nothing
  Next
End Sub

-->
</SCRIPT>
.
.
.
<!-- In the body of the page we have the form. -->
<FORM Name='formName'>
  <SELECT Name='firstSelect'>
    <OPTION Value=''>&nbsp;</OPTION>
    <OPTION Value='NotPrimates'>Not Primates</OPTION>
    <OPTION Value='Primates'>Primates</OPTION></SELECT>

  <SELECT Name='secondSelect'></SELECT>
</FORM>
.
.
.
If you have more options for the first select box, add another array 
and an elseif statement to pick that array out in the 
-firstSelect_onChange- procedure.



© 1999-2004 Synop Pty Ltd