Yet Another Dynamic Drop Down Tutorial
Yet Another Dynamic Drop Down Tutorial

Yet Another Dynamic Drop Down Tutorial

Hey guys. You are probably sick to death of this type of tutorial, but I have found a method that is better than all of them! It creates a multidimensional array and fills in a select box depending on the other select boxes value. I must mention Megan in here for whom I used some aspects of her tutorial: http://tutorial95.easycfm.com/
The benefits of this method is it builds an array from the database and inputs that into the select form. So no need for using switch.

To see this in action go here: http://gcm.syr.edu/cfml/louis/multid.cfm


<cfquery name="getLocal" datasource="#request.dsn#">
SELECT sub.catID,sub.catName,topc.catID AS topID,topc.catName AS topName
FROM subCat sub INNER JOIN topCat topc ON sub.parentID = topc.catID
ORDER BY topName asc,sub.catName asc
</cfquery>

So here we join 2 tables. The sub category table and the top level category. If you use 1 table like that Recursion Tutorial sugests, you can simply join the table onto itself.

<script language="JavaScript1.2">
function populate(obj) {
var subcats = new Array(
<cfoutput query="getLocal" group="topName">
<cfoutput>new Array(#currentrow-1#,"#catID#","#catName#","#topID#")<cfif currentrow NEQ recordcount>,</cfif></cfoutput>
</cfoutput>);

// so the above code is creating a multidimensional array and putting in the values from our query

obj.subcat.options.length = 0;
obj.subcat[0] = null;
var optc = 0;

// here we set the vars.We make sure the subcat select has nothing in it before we add to it. We also create our loop counter called optc

for(i=0;i<subcats.length; i++) {
      if(subcats[i][3] == obj.topcat.value) {
            obj.subcat[optc] = new Option(subcats[i][2],subcats[i][1]);
            optc++;
      } else {
            obj.subcat[0] = new Option("- Please select a category -","null");
      }
}
}


// the above code loops over the array and does an if statement to filter out the array and only fill the select box with subcategories from the selected category. It then increases our counter by 1.
</script>

<form name="myform" action="myactionpage.cfm" method="post">

<select name="topcat" onchange="populate(this.form)"><!-- This is the category selector that will call the function -->
<option>- Select a Category -</option>
<cfoutput query="getLocal" group="topName">
<option value="#topID#">#topName#</option>
</cfoutput>
</select>

<!-- we group the query results by the top level category so that only the top level categories are outputted -->

<select name="subcat">
<option>- Please select a category -</option>
</select>

<!-- This is the sub category select box that gets filled in -->

</form>


Hopefully that worked for you. Contact me if you have any problems at louisstow AT hotmail DOT com (antispam method. im not crazy)



All ColdFusion Tutorials By Author: Louis Stowasser