Hi all,

I am trying to create a drop down form on a webpage where the items that appear in the second drop down box are dependant on what is chosen in the first.

For example, choose country, then state etc.

Can anyone provide some really easy to understand help for me as I am a bif of a novice with JS.

Thanks!!

Jay

Dani AI

Generated

A nice, workable starter from and a clear problem statement from . The pieces below explain how to make that pattern more robust and easier to maintain, plus a compact, modern way to wire the selects so it is safe, accessible, and easier to extend.

Keep these practical points in mind:

  • Put the script after the form elements or run it on DOMContentLoaded so the elements exist before you access them.
  • Store dependent lists in a simple object/JSON (key = country, value = array of items). That makes editing and remote-loading straightforward.
  • When rebuilding the second select, clear existing options, add one default option like "Choose..." and then append new options using createElement (or a DocumentFragment for large lists) instead of repeatedly using innerHTML.
  • Disable the dependent select until a valid choice is picked. That prevents accidental submits.
  • Add a proper <label> for each select and a first option with an empty value so screen readers and keyboard users get a clear starting point.

A short, modern example (replace the IDs with your form IDs):

const data = {
  USA: ['AL|Alabama','AK|Alaska'],
  CAN: ['ON|Ontario','QC|Quebec']
};

const country = document.getElementById('country');
const region  = document.getElementById('state');

country.addEventListener('change', () => {
  region.innerHTML = '<option value="">Choose...</option>';
  const list = data[country.value] || [];
  const frag = document.createDocumentFragment();
  list.forEach(pair => {
    const [val,label] = pair.split('|');
    const opt = document.createElement('option');
    opt.value = val; opt.textContent = label;
    frag.appendChild(opt);
  });
  region.appendChild(frag);
  region.disabled = region.options.length === 1;
});

Accessibility and scaling notes: always include labels and a server-side fallback if the page must work without JavaScript. For very large datasets, load the dependent list on demand via AJAX/Fetch rather than embedding everything. For reference and API details, see the MDN pages on the HTML select element and on addEventListener: select elementaddEventListener.

Quick checklist if it doesn't work: confirm element IDs/names match, check the browser console for errors, ensure the script runs after the DOM is ready, and verify options have value attributes.

Recommended Answers

All 2 Replies

Perhaps this will give you a place to start. Notice the "States" array beginning about line 20; each major group (country, in this case) has an equals (=) sign followed by the code for that group. Within each group are multiple lines each having a code (state, whatever) followed by a semicolon and then the name. The final "=end" is required.

When you select a country, the first function clears any existing State values, then loops through the array to find all States belonging to that country to repopulate the State select list.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html lang="en-US">
  <head>

    <title>Dropdows</title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Script-Type" content="text/javascript" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <meta http-equiv="Content-Language" content="en-US" />
    <meta name="Author" content="James Alarie - jalarie@umich.edu" />
    
    <link rel="icon" href="favicon.ico" />
    <link rev="made" href="mailto:jalarie@umich.edu" />
    
    <script type="text/javascript">
      <!-- Hide this code from non-JavaScript browsers
        States=new Array(
          '=USA',
            "AA;Armed Forces - Americas",           // military
            "AE;Armed Forces - Europe",             // military
            "AP;Armed Forces - Pacific",            // military
            "AL;Alabama",
            "AK;Alaska",
            "AS;American Samoa",                    // territory
            "AZ;Arizona",
            "AR;Arkansas",
            "CA;California",
            "CO;Colorado",
            "CT;Connecticut",
            "DE;Delaware",
            "DC;District of Columbia",              // our nation's capital
            "FM;Federated States of Micronesia",    // territory
            "FL;Florida",
          '=USSR',
            "UK;Ukraine",
            "RS;Russia",
          '=end'
        );
        function DoStates() {
          f1=document.forms[0];                     // abbreviation
          CIndex=f1.Country.selectedIndex;
          CValue=f1.Country.options[CIndex].value;
          for (SIndex=f1.State.length; SIndex>=0; SIndex=SIndex-1) {
            f1.State.options[SIndex]=null;
          }
          CopySwitch='no';
          for (AIndex=0; AIndex<States.length; AIndex++) {
            State=States[AIndex];
            if (State.substring(0,1) == '=') {
              if (State.substring(1) == CValue) {
                CopySwitch='yes';
              } else {
                CopySwitch='no';
              }
            } else {
              SValues=State.split(/;/);
              if (CopySwitch == 'yes') {
                SIndex=f1.State.length;
                f1.State.options[SIndex]=new Option();
                f1.State.options[SIndex].value=SValues[0];
                f1.State.options[SIndex].text=SValues[1];
              }
            }
          }
        } // DoStates
        function PickedState() {
          f1=document.forms[0];                     // abbreviation
          SIndex=f1.State.selectedIndex;
          SValue=f1.State.options[SIndex].value;
          SText=f1.State.options[SIndex].text;
          alert(SValue+': '+SText);
        } // PickedState
      // End hiding -->
    </script>

  </head>

  <body background="jaa_bgnd.jpg" bgcolor="#ffffee" text="black"
      link="blue" vlink="#800088" alink="red">
<!-- Page Header -->
    <div class="header">
      <center><h1>Dropdows</h1></center>
      <hr />
    </div>

<!-- Content -->
    <div class="content">
      <br />
      <noscript>
        <font color="red">
          You must have javascript to make use of this page.
        </font>
      </noscript>
      
      <center>
        <form method="post" action="">
          Country:&nbsp; 
          <select name="Country" id="Country" onchange="DoStates();">
            <option value="">- pick one -</option>
            <option value="USA">United States of America</option>
            <option value="USSR">Union of Soviet Socialist Republics</option>
          </select>
          <br />
          State:&nbsp; 
          <select name="State" id="State" onchange="PickedState();">
            <option value="">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </option>
          </select>
          <br />
          <input type="reset" value=" Reset " title=" Reset " />
        </form>
        
      </center>
  
    </div>
  
<!-- Page Footer -->
    <div class="footer">
      <br clear="all" /><hr />
      Written on September 12, 2006, by:&nbsp;
      <a href="mailto:jalarie@umich.edu">James Alarie</a>
    </div>

  </body>

</html>

Excellent! Thank you so much for your help!! It is very much appreciated.

Jay

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.