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>
   <optGroup label="Canada" id="CA">
      <option value="TO">Toronto</option>
      <option value="ON">Ontario</option>
   </optGroup>
   <optGroup label="Mexico" id="MX">
      <option value="MO">Morales</option>
      <option value="PV">Puerto Vallerta</option>
   </optGroup>
</select>

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.

4 comments:

  1. You ought to dependably run with a moneylender that is straightforward and really inspired by helping you with your present circumstance.Payday Loans San-diego

    ReplyDelete
  2. I have learnt HTML Coding in my work station. It helps me a lot to upload a document for article writing. So i would like to learn next level of coding to improve myself in my work station. Can you please suggest me what kind of training i need for my work. Expecting a reply. Thank you

    ReplyDelete
  3. In any case, on the off chance that you pick a shipper loan, installments are ascertained as a level of Visa deals, and if the deals are developing, the re-installment could be snappier,check cashing near me open now san diego

    ReplyDelete