www.webdeveloper.com
Results 1 to 4 of 4

Thread: Dynamic Drop-down (select tag) conditional list

  1. #1
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330

    Lightbulb Dynamic Drop-down (select tag) conditional list

    I have noticed a few requests lately on the forum where there is a request for a dynamic dropdown list (<select...> tag)
    that would display one set of options if one condition is met, but a different set of options if a different condition is chosen.

    This is my attempt to solve this problem for other users.
    The following code is a template to show one way of how this question could be resolved.
    Code:
    <html>
    <head>
    <title>Selected Option Displays</title>
    <script type="text/javascript">
    
    /* Array format:  Select Display | Array display | Include items
       Select Display is <select id...> element to populate
       Array Display is array containing information to populate next element
       Include Items of Array Display to populate the <select id...> tag
    */
    var Options1 = [
    	'-- Select --||0',
    	'Opt 2: 1. All|Options2|0,1,2,3,4,5,6',
    	'Opt 2: 2. Even|Options2|0,2,4,6',
    	'Opt 2: 3. Odd|Options2|0,1,3,5'	// Note: no comma after last entry
    ];
    	
    var Options2 = [
    	'-- Select --||0',
    	'Opt 3: 1. All|Options3|0,1,2,3,4,5,6,7,8,9,10',
    	'Opt 3: 2. Odd|Options3|0,1,3,5,7,9',
    	'Opt 3: 3. Even|Options3|0,2,4,6,8,10',
    	'Opt 3: 4. Threes|Options3|0,3,6,9',
    	'Opt 3: 5. Fours|Options3|0,4,8',
    	'Opt 3: 6. Fives|Options3|0,5,10'	// Note: no comma after last entry
    ];
    
    var Options3 = ['-- Select --||0',
                    ' 1 A||',' 2 B||',' 3 C||',' 4 D||',' 5 E||',
                    ' 6 F||',' 7 G||',' 8 H||',' 9 I||','10 J||'];
    
    Array.prototype.exists = function (x) {
      for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
      }
      return false;
    }
    
    function Populate(IDS,itemArr,incItems) {		
      var selElem = document.getElementById(IDS);
      selElem.options.length = 0;  var k = 0;
      var tarr = [];  var bypass = [];		// temporary holding arrays
      
      if (incItems == '') {				// current selections -- show all if blank
        for (var i=0; i<itemArr.length; i++) {
          tarr = itemArr[i].split('|');		// create display, itemArray, include items
          selElem.options[selElem.options.length] = new Option(tarr[0],itemArr[i]);
        }
      } else {
        tarr = incItems.split('|');
    //    bypas = tarr[1];
        bypass = tarr[2].split(',');		
        for (var j=0; j<bypass.length; j++) {
          k = bypass[j];				// get entry to create item
          tarr = itemArr[k].split('|');  		// create display, itemArray, include items
          selElem.options[selElem.options.length] = new Option(tarr[0],itemArr[k]);
        }
      }
    }
    
    function elem(IDS) { return document.getElementById(IDS); }
    function ChoiceDisplay() {	// for testing purposes only
      var str = 'Test display of choice results:\n';
      str += elem('Options1').value+'\n';
      str += elem('Options2').value+'\n';
      str += elem('Options3').value;
      alert(str);
    }
    
    </script>
    </head>
    <body onload="Populate('Options1',Options1,'')"> <!-- Initialize to ALL options -->
    <!-- Use next "onload" if desire is to initialize to fewer than all item -->
    <!-- body onload="Populate('Options1',Options1,'|Options1|0,1,2,3')" --> 
    
      Option1: <select id="Options1" onchange="Populate('Options2',Options2,this.value)"></select>
               <button onclick="alert(elem('Options1').value)">1</button>
      <p>
      Option2: <select id="Options2" onchange="Populate('Options3',Options3,this.value)"></select>
               <button onclick="alert(elem('Options2').value)">2</button>
      <p>
      Option3: <select id="Options3"></select>
               <button onclick="alert(elem('Options3').value)">3</button>
      <p>
      <button onclick="ChoiceDisplay()">Display Choices</button>
    </body>
    </html>
    I'm currently working on an iMac, so the script has only been tested in FF and Safari browsers.
    I'll test with MSIE later when I have access to a different PC.

    Might be possible to tighten the code a bit more, but for ease of understanding I think this is good enough as a first attempt.
    Should be able to go beyond 3 levels of choices if desired.

    It should be fairly easy to modify the 'Options1, Option2, Options3 (etc) arrays to create the conditional conditions for a particular display for the user to select the options.
    The options are dummy choices to show how the following displays are created with the particular list items to show on NEXT level.

    Post back questions if the comments in the script are not complete enough.

    Good Luck!

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,330

    Lightbulb Example of use

    To demonstrate how the template might be modified,
    here is a (simply-stupid) example of meal choices with the conditional drop-down display.
    Code:
    <html>
    <head>
    <title>Selected Option Displays</title>
    <script type="text/javascript">
    
    /* Array format:  Select Display | Array display | Include items
       Select Display is <select id...> element to populate
       Array Display is array containing information to populate next element
       Include Items of Array Display to populate the <select id...> tag
    */
    var Options1 = [
    	'-- Select --||0',
    	'Fruits|Options2|0,1,2',
    	'Vegetables|Options2|0,3,4,5',
    	'Meats|Options2|0,6,7',
    	'Fish||0,8,9',
    	'Desserts||0,10,11'
    // Note: no comma after last entry
    ];
    	
    var Options2 = [
    	'-- Select --||0',
    	'Green|Options3|1,2',			// Fruit (1)
    	'Red|Options3|3,4',
    	'Green|Options3|5,6,7',			// Vegetables (3)
    	'Red|Options3|8',
    	'Yellow|Options3|9',
    	'Red|Options3|10,11',			// Meat	(6)
    	'White|Options3|12,13,14',
    	'Fresh water|Options3|15,16',	// Fish	(8)
    	'Salt Water|Options3|17,18',
    	'Cookies|Options3|19,20,21',	// Desserts (10)
    	'Ice Cream|Options3|22,23,24'
    // Note: no comma after last entry
    ];
    
    var Options3 = ['-- Select --||0',
    				'Green Apples||',	// Fruit (1)
    				'Kiwi||',
    				'Strawberries||',
    				'Cherries||',
                    'Celery||',			// Vegatables (5)
                    'Spinach||',
                    'Lettuce||',
                    'Bell pepper||',
                    'Squash||',
                    'Beef||',			// Meat (10)
                    'Hamberger||',
                    'Chicken||',
                    'Turkey||',
                    'Pork||',
                    'Trout||',			// Fish (15)
                    'Catfish||',
                    'Red Fish||',
                    'Grouper||',
                    'Sugar||',			// Cookies (19)
                    'Oatmeal-Rasin||',
                    'Molassas||',
                    'Vanilla||',		// Ice Cream
                    'Chocolate||',
                    'Strawberry||'
    ];
    
    Array.prototype.exists = function (x) {
      for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
      }
      return false;
    }
    
    function Populate(IDS,itemArr,incItems) {		
      var selElem = document.getElementById(IDS);
      selElem.options.length = 0;  var k = 0;
      var tarr = [];  var bypass = [];		// temporary holding arrays
      
      if (incItems == '') {				// current selections -- show all if blank
        for (var i=0; i<itemArr.length; i++) {
          tarr = itemArr[i].split('|');		// create display, itemArray, include items
          selElem.options[selElem.options.length] = new Option(tarr[0],itemArr[i]);
        }
      } else {
        tarr = incItems.split('|');
    //    bypas = tarr[1];
        bypass = tarr[2].split(',');		
        for (var j=0; j<bypass.length; j++) {
          k = bypass[j];				// get entry to create item
          tarr = itemArr[k].split('|');  		// create display, itemArray, include items
          selElem.options[selElem.options.length] = new Option(tarr[0],itemArr[k]);
        }
      }
    }
    
    function elem(IDS) { return document.getElementById(IDS); }
    function ChoiceDisplay() {	// for testing purposes only
      var str = 'Test display of choice results:\n';
      str += elem('Options1').value+'\n';
      str += elem('Options2').value+'\n';
      str += elem('Options3').value;
      alert(str);
    }
    
    </script>
    </head>
    <body onload="Populate('Options1',Options1,'')"> <!-- Initialize to ALL options -->
    <!-- Use next "onload" if desire is to initialize to fewer than all item -->
    <!-- body onload="Populate('Options1',Options1,'|Options1|0,1,2,3')" --> 
    
      Option1: <select id="Options1" onchange="Populate('Options2',Options2,this.value)"></select>
               <button onclick="alert(elem('Options1').value)">1</button>
      <p>
    
      Option2: <select id="Options2" onchange="Populate('Options3',Options3,this.value)"></select>
               <button onclick="alert(elem('Options2').value)">2</button>
      <p>
      Option3: <select id="Options3"></select>
               <button onclick="alert(elem('Options3').value)">3</button>
      <p>
      <button onclick="ChoiceDisplay()">Display Choices</button>
    
    </body>
    </html>
    Can be used with any conditional list for the user to select from.
    Can also be expanded beyond 3 levels.
    And you can modify the "ChoiceDisplay" function to decode the specify choice of the user at any level.

  3. #3
    Join Date
    Jul 2013
    Posts
    1
    Hi! Your code is nice and it' s just what I need. My question is: How to get selected option into php variable by clicking on the button. This is only part of my program that will use javascript, everything else will be done with php. About java I know nothing, so please can You help me.

  4. #4
    Join Date
    Mar 2007
    Location
    U.K.
    Posts
    1,127
    There are various array-based solutions around already.

    • To allow degraded operation, the options of the first <select> should always be marked-up by default, not populated by the script itself.
    • For clarity of operation, all unused submenus should be de-populated and optionally hidden.
    • To help non-programmers, the array format should be as intuitive as possible. Here's an example that uses multiple arrays wrapped in a single object, with the name of each array specifying the corresponding option hierarchy to which its options apply.
    • Installation should be unobtrusive.

    In reply to leoleo, ensure the elements are within a form and use a submit button. Provided the <select>s have a name attribute, their values will be transmitted.
    Where used, return should be executed unconditionally and always as the last statement in the function.

    That's my signature, it's not part of the damn post!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles