/    Sign up×
Community /Pin to ProfileBookmark

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>
[/code]

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!
?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERauthorJan 15.2010 — To demonstrate how the template might be modified,

here is a (simply-stupid) example of meal choices with the conditional drop-down display.
<i>
</i>&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Selected Option Displays&lt;/title&gt;
&lt;script type="text/javascript"&gt;

/* Array format: Select Display | Array display | Include items
Select Display is &lt;select id...&gt; element to populate
Array Display is array containing information to populate next element
Include Items of Array Display to populate the &lt;select id...&gt; 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 &lt; 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&lt;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&lt;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);
}

&lt;/script&gt;
&lt;/head&gt;
&lt;body onload="Populate('Options1',Options1,'')"&gt; &lt;!-- Initialize to ALL options --&gt;
&lt;!-- Use next "onload" if desire is to initialize to fewer than all item --&gt;
&lt;!-- body onload="Populate('Options1',Options1,'|Options1|0,1,2,3')" --&gt;

Option1: &lt;select id="Options1" onchange="Populate('Options2',Options2,this.value)"&gt;&lt;/select&gt;
&lt;button onclick="alert(elem('Options1').value)"&gt;1&lt;/button&gt;
&lt;p&gt;

Option2: &lt;select id="Options2" onchange="Populate('Options3',Options3,this.value)"&gt;&lt;/select&gt;
&lt;button onclick="alert(elem('Options2').value)"&gt;2&lt;/button&gt;
&lt;p&gt;
Option3: &lt;select id="Options3"&gt;&lt;/select&gt;
&lt;button onclick="alert(elem('Options3').value)"&gt;3&lt;/button&gt;
&lt;p&gt;
&lt;button onclick="ChoiceDisplay()"&gt;Display Choices&lt;/button&gt;

&lt;/body&gt;
&lt;/html&gt;

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.
Copy linkTweet thisAlerts:
@leoleoJul 21.2013 — 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.
Copy linkTweet thisAlerts:
@Logic_AliJul 21.2013 — There are various array-based solutions around already.

[LIST]
  • [*]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.

  • [/LIST]

    In reply to [I]leoleo[/I], ensure the elements are within a form and use a submit button. Provided the <select>s have a [I]name[/I] attribute, their values will be transmitted.
    Copy linkTweet thisAlerts:
    @rpaulyOct 07.2014 — Hi,

    Thanks for the code!

    But when I add a form to the above only 1 value 'Option1' gets transmitted.

    Here is what I tried:

    <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')" -->

    <form id="select_form" method="post" action="capture_from_form_test.php">

    Option1: <select id="Options1" name="Options1" onchange="Populate('Options2',Options2,this.value)"></select>

    <button onclick="alert(elem('Options1').value)">1</button>

    <p>



    Option2: <select id="Options2" name="Options2" onchange="Populate('Options3',Options3,this.value)"></select>

    <button onclick="alert(elem('Options2').value)">2</button>

    <p>

    Option3: <select id="Options3" name="Options3"></select>

    <button onclick="alert(elem('Options3').value)">3</button>

    <p>

    <button onclick="ChoiceDisplay()">Display Choices</button>

    <input type="submit" value="confirm" /> <input type="reset" value="Clear">

    </form>

    </body>

    </html>
    ×

    Success!

    Help @JMRKER spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.29,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...