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.


  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai

    Online Java Training Java Online Training | Java J2EE Online Training | JavaEE Training Institute in Chennai

  2. 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

  3. 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

  4. 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