Jump to Real's How-to Main page

Initialize a SELECT "on the fly"

<HTML>
<HEAD>
<SCRIPT>
var arrCanada = 
   new Array("Quebec", "Ontario", "Alberta", "Nova Scotia");
var arrUSA = 
   new Array("Alabama", "North Dakota", "New York", "Ohio");

 
function setProvState() {
 var selectCountry = document.theForm.country;
 var selectProvState = document.theForm.provstate;
 var theCountry = selectCountry.options[selectCountry.selectedIndex].value;
 if (theCountry == "canada"){
    selectProvState.options.length = 0;
    for(var i=0; i<arrCanada.length; i++)
      selectProvState.options[selectProvState.options.length] 
         = new Option(arrCanada[i]);
      selectProvState.options[0].selected = true;
    }
 
 if (theCountry == "usa"){
    var selectProvState = document.theForm.provstate;
    selectProvState.options.length = 0;
    for(var i=0; i<arrUSA.length; i++)
      selectProvState.options[selectProvState.options.length] 
         = new Option(arrUSA[i]);
      selectProvState.options[0].selected = true;
    }
 }
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="theForm" METHOD="POST">
Country: 
<SELECT NAME="country" onChange="setProvState()">
   <OPTION VALUE="canada">Canada
   <OPTION VALUE="usa">USA
 </SELECT>
Prov/State:
<SELECT NAME="provstate">
   <OPTION>--------------------
   <OPTION>
   <OPTION>
   <OPTION>
   <OPTION>
 </SELECT>
</FORM>
</BODY>
</HTML>

Try it :

Country: Prov/State:

If you find this article useful, consider making a small donation
to show your supportfor this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]