Data AccessCore JavaApp FrameworksViewTestingBuildingDeploymentDev ToolsSecurityOpinions

Monday, November 2, 2009

Traversing through HTML <optgroups> and <options> in Javascript

I've posted some HTML + Javascript code to traverse through <optgroups> and <options> in Javascript.

Supposed we had a State/Province drop down box with the following entries:

That was created with the following HTML:
<select name="theCountryState" id="theCountryState">
   <optGroup label="United States" id="US">
      <option value="NY">New York</option>
      <option value="MO">Missouri</option>
   <optGroup label="Canada" id="CA">
      <option value="TO">Toronto</option>
      <option value="ON">Ontario</option>
   <optGroup label="Mexico" id="MX">
      <option value="MO">Morales</option>
      <option value="PV">Puerto Vallerta</option>

The appropriate option can be selected easily by traversing through the OPTGROUPS and OPTIONS.

function selectCorrectOption(var countrySelected, var stateSelected) {
   //Traverse through Option Groups and options and mark correct option.
   countryStateOptGroups = document.getElementById("theCountryState").childNodes;
   for(i = 0; i < countryStateOptGroups.length; i++)
      if(countryStateOptGroups[i].id == countrySelected){
         stateOptions = countryStateOptGroups[i].childNodes;
         for(j = 0; j < stateOptions.length; j++){
            if(stateOptions[j].value == stateSelected){
               stateOptions[j].selected = true;

Any questions, please feel free to comment.