Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Jun 2010
    Posts
    30
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Dynamic Drop Down Menus

    Hi,

    I am trying to use JavaScript for several linked drop down menus. The contents of the first drop down menu is defined in the code of the form, however, I do not know the best way to populate the following drop down menus depending on the selection of the previous.

    I have something working with the following JavaScript code, however as there are lots of options I am not sure whether this is the best way of doing this.

    Code:
     <script type="text/javascript">
    
    function setYear(chosen, selbox) {
     
    selbox.options.length = 0;
    if (chosen == " ") {
      selbox.options[selbox.options.length] = new Option('Please select a year',' ');
    setTimeout(setYear(' ',document.question.subject),5);
     
    }
    if (chosen == "1") {
      selbox.options[selbox.options.length] = new
    Option('exam1','11');
      selbox.options[selbox.options.length] = new
    Option('exam2','12');
    selbox.options[selbox.options.length] = new
    Option('exam3','13');
    selbox.options[selbox.options.length] = new
    Option('exam4','14');
    selbox.options[selbox.options.length] = new
    Option('exam5','15');
    setTimeout(setYear('11',document.question.subject),5);
    
    }
    
    
    
    
    if (chosen == "2") {
      selbox.options[selbox.options.length] = new
    Option('exam6','twoone');
      selbox.options[selbox.options.length] = new
    Option('exam7','twotwo');
     selbox.options[selbox.options.length] = new
    Option('exam8','twothree');
     selbox.options[selbox.options.length] = new
    Option('exam8','twofour');
     selbox.options[selbox.options.length] = new
    Option('exam9','twofive');
     selbox.options[selbox.options.length] = new
    
    }
    if (chosen == "3") {
      selbox.options[selbox.options.length] = new
    Option('exam10','threeone');
      selbox.options[selbox.options.length] = new
    Option('exam11','threetwo');
      selbox.options[selbox.options.length] = new
    Option('exam12','threethree');
      selbox.options[selbox.options.length] = new
    
    }
    
    
    if (chosen == "11") {
      selbox.options[selbox.options.length] = new
    Option('subject1','111');
    }
    
    
    }
    
    
    </script>
    This is what I have in the form:
    Code:
       
            <td>Minimum DBS Year: </td><td colspan="2">
         <select name="DBSyear" onchange="setYear(document.question.DBSyear.options
    [document.question.DBSyear.selectedIndex].value,
    document.question.exam);">
    <option value=" " selected="selected"> </option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    </select>
    		</tr>
    		<tr>
    		<td>
    		Exam Paper:
    		</td>
    		<td>
    		 <select name="exam" onchange="setYear(document.question.exam.options
    [document.question.exam.selectedIndex].value,
    document.question.subject);">
    <option value=" " selected="selected">Please select a year</option>
    </select>
    </td>
    		</tr>
    		<tr>
    		<td>
    		Subject:
    		</td>
    		<td>
    		<select name="subject" size="1">
    <option value=" " selected="selected">Please select an exam</option>
    </select>
    		</td>
    		</tr>

    How would I populate the drop down menus from tables in the database and filter the options depending on the previous drop down selection??

    I would appreciate any help!

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Here is an example which you can adapt:-

    Code:
    <html> 
    <head> 
    <script type = "text/javascript">
     
    function setOptions(opt) { 
    var select2 = document.myform.select2; 
    select2.options.length = 0; 
    
    if (opt == "0"){
    select2.options[select2.options.length] = new Option(""); 
    }
    
    if (opt == "1") { 
    select2.options[select2.options.length] = new Option('Select A State');
    select2.options[select2.options.length] = new Option('New York'); 
    select2.options[select2.options.length] = new Option('California'); 
    select2.options[select2.options.length] = new Option('Texas'); 
    select2.options[select2.options.length] = new Option('Arizona'); 
    
    } 
    if (opt == "2") { 
    select2.options[select2.options.length] = new Option('Select A Province');
    select2.options[select2.options.length] = new Option('Nova Scotia'); 
    select2.options[select2.options.length] = new Option('Ontario'); 
    select2.options[select2.options.length] = new Option('Alberta'); 
    select2.options[select2.options.length] = new Option('British Colombia'); 
    
    } 
    if (opt == "3") { 
    select2.options[select2.options.length] = new Option('Select A State');
    select2.options[select2.options.length] = new Option('New South Wales'); 
    select2.options[select2.options.length] = new Option('Queensland');
    select2.options[select2.options.length] = new Option('Victoria'); 
    select2.options[select2.options.length] = new Option('Western Australia'); 
    
    } 
    } 
    </script> 
    </head> 
    <body> 
    
    <form name="myform"> 
    <select name="select1" size="1"  style="width: 150px" onchange="setOptions(document.myform.select1.options[document.myform.select1.selectedIndex].value);"> 
    <option value="0" selected>Select A Country</option> 
    <option value="1">USA</option> 
    <option value="2">Canada</option> 
    <option value="3">Australia</option> 
    </select> 
    <br /> 
    <br /> 
    <select name="select2" size="1"  style="width: 150px" > 
    <option value = "0"></option>
    </select> 
    
    </form> 
    
    </body> 
    </html>
    "His lack of education is more than compensated for by his keenly developed moral bankruptcy." - Woody Allen - US movie actor, comedian, & director (1935 - )

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Here's how I do it. See next post for why this works well for DB-based situations.
    Code:
    <html> 
    <head> 
    <title>Category and Subcategory Drop Down Lists Via JavaScript</title> 
    <script type="text/javascript">
    
    // constructor for a SubCat object:
    function SubCat( cn, scn, scnm )
    {
        this.CatNum     = cn;
        this.SubcatNum  = scn;
        this.SubcatName = scnm;
    }
    
    // *************************************************************** 
    // establish the array of subcategory info: 
    var subcatInfo = [ 
        new SubCat('1001','3','Beans'),
        new SubCat('1001','4','Corn'),
        new SubCat('1001','5','Miscellaneous'),
        new SubCat('1001','2','Potato'),
        new SubCat('1001','1','Tomato'),
        new SubCat('1002','2','Bran'),
        new SubCat('1002','1','Corn Flakes'),
        new SubCat('1002','6','Miscellaneous'),
        new SubCat('1002','3','Oatmeal'),
        new SubCat('1002','5','Pre-sweetened'),
        new SubCat('1002','4','Rice'),
        new SubCat('1003','5','Miscellaneous'),
        new SubCat('1003','4','Pasta'),
        new SubCat('1003','2','Rice'),
        new SubCat('1003','3','Sugar'),
        new SubCat('1003','1','Wheat'),
        new SubCat('1004','2','Artificial fruit drinks'),
        new SubCat('1004','3','Colas'),
        new SubCat('1004','5','Diet drinks'),
        new SubCat('1004','1','Fruit juices'),
        new SubCat('1004','6','Miscellaneous'),
        new SubCat('1004','4','Root beers'),
        new SubCat('1005','4','Cookies'),
        new SubCat('1005','2','Corn chips'),
        new SubCat('1005','5','Crackers'),
        new SubCat('1005','7','Dips'),
        new SubCat('1005','6','Meat products'),
        new SubCat('1005','3','Popcorn'),
        new SubCat('1005','1','Potato Chips'),
        new SubCat('1006','2','Boxed Chocolates'),
        new SubCat('1006','4','Bulk candies'),
        new SubCat('1006','1','Chocolate'),
        new SubCat('1006','5','Gum'),
        new SubCat('1006','3','Hard candies'),
        new SubCat('1006','6','Other'),
        new SubCat('1007','8','Cakes'),
        new SubCat('1007','9','Cakes, custom decorated'),
        new SubCat('1007','7','Donuts'),
        new SubCat('1007','11','Other'),
        new SubCat('1007','10','Pies'),
        new SubCat('1007','5','Ryes, etc.'),
        new SubCat('1007','6','Speciaty breads, Bakery'),
        new SubCat('1007','3','Wheat'),
        new SubCat('1007','4','Wheat, Bakery'),
        new SubCat('1007','1','White'),
        new SubCat('1007','2','White, Bakery') 
        ]; 
    
    // *************************************************************** 
    
    // this funcion is called upon a change of main category 
    function doCategory(sel) 
    { 
        var ix; 
        var subcat = sel.form.SubcategorySelect; 
    
        // regardless of what else we do, we wipe out all the 
        // options in the subcategory dropdown by
        // going backwards, removing selected options 
        for ( ix = subcat.options.length - 1; ix >= 0; --ix ) 
        { 
            subcat.options[ix] = null; 
        } 
        // now, did the user select a category? 
        if ( sel.selectedIndex == 0 ) 
        { 
            // no...so give user the "no subcats" msg 
            subcat.options[0] = 
                new Option("-- no subcategories yet --","0"); 
            return; // and we are done 
        } 
        // yes, so get the appropriate subcategories: 
        subcat.options[0] = 
            new Option("-- choose a subcategory below --","0"); 
    
        // what category number was selected?
        var catnum = sel.options[sel.selectedIndex].value; 
        var cursc = 0; 
        for ( ix = 0; ix < subcatInfo.length; ++ix ) 
        { 
            // looking for all subcat's with the requested category number
            var subcatObj = subcatInfo[ix]; 
            if ( subcatObj.CatNum == catnum ) 
            { 
                subcat.options[++cursc] = 
                    new Option( subcatObj.SubcatName, subcatObj.SubcatNum );
            } 
        } 
    } 
    // done with JS code 
    </script>
    </head>
    <body>
    <form>
    First select a category and then, when the list of subcategories 
    appears, select a subcategory:
    <br/><br/>
    <select name="CategorySelect" onchange="doCategory(this);"> 
    <option Value="NONE">-- choose a category below--</option> 
    <option Value='1007'>Breads</option>
    <option Value='1006'>Candies</option>
    <option Value='1001'>Canned goods</option>
    <option Value='1002'>Cereal</option>
    <option Value='1004'>Drinks</option>
    <option Value='1005'>Snack foods</option>
    <option Value='1003'>Staples</option>
    </select>
    &nbsp;&nbsp;
    <select name="SubcategorySelect"> 
        <option Value="0">-- no subcategories yet -- 
    </select> 
    </form> 
    </body>
    </html>
    Last edited by Old Pedant; 07-26-2010 at 10:07 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    This demo was originally derived from data in a simple DB table. (Happens to have been done in ASP, but obviously works as well for PHP or JSP or whatever.)

    The DB schema was pretty simple:
    Code:
    In mySQL terms:
    
    CREATE TABLE categories (
       catid int auto_increment primary key,
       catname varchar(255)
       );
    
    CREATE TABLE subcategories (
       subcatid auto_increment primary key,
       catid int FOREIGN KEY references categories(catid),
       subcatname varchar(255)
       );
    So to create that array in the HTML that I showed:
    Code:
    var subcatInfo = [ 
        new SubCat('1001','3','Beans'),
        new SubCat('1001','4','Corn'),
        new SubCat('1001','5','Miscellaneous'),
        ... etc. ...
    All I needed to do was a query like this:
    Code:
        SELECT catid, subcatid, subcatname 
        FROM subcategories
        ORDER BY catid, subcatname
    And then I just dumped out each resulting record, one at a time, in the JS code.

    I do *NOT* use PHP, but roughly something like this:
    Code:
    <script type="text/javascript">
    var subcatInfo = [ 
    <?php
       $sql = "SELECT catid, subcatid, subcatname FROM subcategories ORDER BY catid, subcatname";
       $data = mysql_query($sql);
       while ( $row = mysql_fetch_array($data) )
       {
            echo "   new SubCat('$row[0]','$row[1]','$row[2]'),\n";
       }
    ?>
        new SubCat('xxxx','x','x')
        ];
    </script>
    Or something along those lines.

    DIRT EASY!!! Uncomplicated. Easy to code, easy to follow.

    And, of course, you can use PHP to generate the first <select> from the Categories table, as well.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New Coder
    Join Date
    Jun 2010
    Posts
    30
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Thank you very much! I will try it out now and let you know how I get on!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •