ASP Code, DHTML Code, JavaScript Code, PHP Code

Dynamically Populating Select Menus Client-Side With JavaScript

This JavaScript function will enable your web application to populate a drop-down menu of items on the fly, based on the selection of another list, without reloading the page. I also provide the code to build the arrays by loading them from a database with ASP and PHP.

The ASP code builds JavaScript array of all possible items that could be populated into the second menu. For each item in the array, it indicates the item in the first menu with which it is associated. So then when the user selects an item in the first list, the function takes the selected value, iterates through the array to find only those items associated with the selected value, and loads them into the second menu.

Here's the HTML code of the form with the two drop down lists. I've hard-coded the first menu, but you can also store and load those values from a database, based on the code I'm going to provide:


<form name="form1">
    <select name="types" onChange="fillItems(0)">
        <option value="32">Laptops</option>
        <option value="21">PDAs</option>
    </select>
    <select name="items"></select>
</form>

Here's the ASP code to build the array of possible menu items:


<script language="JavaScript">
var arItems = new Array()
arItems = [
<%
    strSQL = "SELECT type_id, id, description FROM items"
    objRS.Open strSQL, strConn
       arItems = objRS.GetRows()
    objRS.Close()

    for i = 0 to uBound( atItems, 2 )
        response.Write( "&#91;" & atItems( 0, i ) & "," & atItems( 1, i ) & ",'" & atItems( 2, i ) & "'&#93;" )
        if i < uBound( atItems, 2 ) then response.Write("," & vbCrLf )
    next
%>
]

Here's the PHP code to build the array of possible menu items:


var arItems = new Array()
arItems = [
<?php
include_once("connection.php");
$query = "SELECT type_id, id, description FROM items";
$result = mysql_query($query);
$num_rows = mysql_num_rows( $result );
$i = 1;
while ($row_result = mysql_fetch_row($result)) {
    echo "&#91;'".$row_result&#91;0&#93;."', '".$row_result&#91;1&#93;."', '".$row_result&#91;2&#93;."'&#93;";
    if ( $i < $num_rows )
        echo ", 
        ";
    $i++;
}
?>
]

This will produce a JavaScript array that looks like this:


arItems = [
    [ 32, 234, 'Toshiba Laptops'],
    [ 32, 156, 'Compaq Laptops'],
    [ 32, 333, 'Sony Laptops'],
    [ 21, 656, 'IBM PDAs'],
    [ 21, 467, 'Palm PDAs']
]

And finally, here's the JavaScript function used to populate the second menu:

function fillItems(intStart) {
var fTypes = document.form1.types;
var fItems = document.form1.items;
var a = arItems;
var b, c, d, intItem, intType

if ( intStart > 0 ) {
for ( b = 0; b < a.length; b++ ) { if ( a[b][1] == intStart ) intType = a[b][0]; } for ( c = 0; c < fTypes.length; c++ ) { if ( fTypes.options[ c ].value == intType ) fTypes.selectedIndex = c; } } if ( intType == null ) intType = fTypes.options[ fTypes.selectedIndex ].value; fItems.options.length = 0; for ( d = 0; d < a.length; d++ ) { if ( a[d][0] == intType ) fItems.options[ fItems.options.length ] = new Option( a[d][2], a[d][1] ); if ( a[d][1] == intStart ) fItems.selectedIndex = fItems.options.length - 1; } } [/code]

Share

13 Comments

  1. Hi,

    I am testing this code for three dependent menu levels, however, it does not populate the third menu. Could you please, tell me what is wrong in my code:

    Untitled Document

    function fillItems(intStart) {
    var fTypes = document.form1.state;
    var fItems = document.form1.county;
    var a = arItems;
    var b, c, d, intItem, intType

    if ( intStart > 0 ) {
    for ( b = 0; b
    ]

    function fillcity(intStart) {
    var fTypes2 = document.form1.county;
    var fItems2 = document.form1.city;
    var a = arItems2;
    var b, c, d, intItem, intType

    if ( intStart > 0 ) {
    for ( b = 0; b

    ]

    NSW
    QLD
    VIC

    Choose District

    Choose Suburb

    Thank you,

    Andrew

  2. for starters, you're closing your for loops with square brackets instead of curly brackets…

  3. I want select division then related district come and when select district the ralated post code come in a different list menu. Please help me to solve this php code..

    Untitled Document

    ">

    ">

    function fillItems(intStart) {
    var fTypes = document.form1.state;
    var fItems = document.form1.county;
    var a = arItems;
    var b, c, d, intItem, intType

    if ( intStart > 0 ) {
    for ( b = 0; b
    }

    function fillcity(intStart) {
    var fTypes2 = document.form1.county;
    var fItems2 = document.form1.city;
    var a = arItems2;
    var b, c, d, intItem, intType

    if ( intStart > 0 ) {
    for ( b = 0; b
    }

  4. ">

    ">

    function fillItems(intStart) {
    var fTypes = document.form1.state;
    var fItems = document.form1.county;
    var a = arItems;
    var b, c, d, intItem, intType

    if ( intStart > 0 ) {
    for ( b = 0; b
    }

    function fillcity(intStart) {
    var fTypes2 = document.form1.county;
    var fItems2 = document.form1.city;
    var a = arItems2;
    var b, c, d, intItem, intType

    if ( intStart > 0 ) {
    for ( b = 0; b
    }

  5. I dont understand how to put this all together, is it in one html document? or all seperatly for instance. php code saved in as php html speerate? I very much a beginer, can some one explain how you would get this working? – sam thanks

  6. well, the code to pull the data from a database and populate the javascript array would need to be done with PHP, whether in that file or a separate one. Then the javascript would be onpage

    If you're very much a beginner, this might be a little beyond you right now. I encourage you to keep coding!

  7. You REALLY need to fix the stylesheet for the code sections… I can't see white text on a white background unless I highlight it!

    Cheers!

  8. Very legibile. Is it a coloring competition?

  9. Hi,

    I have been trying to use Spry to do this for a couple of days. I found your script and within 10 minutes I had it populating both dropdown lists from my database and working spot on. Great script. Thanks

  10. Can you provide the code to get the arrays from a database in Coldfusion. I too am a biginner, to Coldfusion, but need to populate dynamic drop downs

  11. I came across your script after many hours of searching. Works like a charm. Thank you very much!

  12. REALLY NEEDED THIS… SO HAPPY I FOUND THIS PAGE SOMEHOW THANKS TO GOOGLE AND THROUGH SOME MAGICAL COMBINATION OF KEYWORDS!!!! 4 Years almost to the day and this thing still works like a charm… IOU!!!! <3 <3 <3

  13. Would it be possible to pass php variables ie laptops and compaq laptops to preselect both selects on page load? Then on changing the first select from laptops to PDAs it triggers the onchange.
    I know populating the first select is easy but populating the second by passing the var to javascript and selecting onload is probably impossible?

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image