I'm building a form that includes a section for auto makes/models. When a user chooses a make ("Ford", "BMW", etc), I want the model box to automatically change to show only cars of that make. I have all of the data, but I have no idea how to make the drop-down boxes behave that way. Where do I start?
I have written the following as an example for you: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title></title> <script type="text/javascript"> var makes = new Array("BMW", "Ford"); var models = new Array(); models["BMW"] = new Array("318", "525", "650", "X5"); models["Ford"] = new Array("Bronco", "Explorer", "Focus"); function resetForm(theForm) { /* reset makes */ theForm.makes.options[0] = new Option("Please select a make", ""); for (var i=0; i<makes.length; i++) { theForm.makes.options[i+1] = new Option(makes[i], makes[i]); } theForm.makes.options[0].selected = true; /* reset models */ theForm.models.options[0] = new Option("Please select a model", ""); theForm.models.options[0].selected = true; } function updateModels(theForm) { var make = theForm.makes.options[theForm.makes.options.selectedIndex].value; var newModels = models[make]; theForm.models.options.length = 0; theForm.models.options[0] = new Option("Please select a model", ""); for (var i=0; i<newModels.length; i++) { theForm.models.options[i+1] = new Option(newModels[i], newModels[i]); } theForm.models.options[0].selected = true; } </script> </head> <body> <form name="autoSelectForm" action="" method="post"> <select size="1" name="makes" onchange="updateModels(this.form)"> </select> <select size="1" name="models"> </select> <input type="submit"> </form> <script type="text/javascript"> resetForm(document.autoSelectForm); </script> <?php $make = $_POST['makes']; $model = $_POST['models']; if ($make && $model) { echo "<p>".$make." - ".$model."</p>"; } ?> </body> </html> PHP: The PHP is just to display what is submitted using the form. This is just a fairly simple example of a hierarchical select menu, populated with the arrays set up at the top of the script. I put in some example makes and models that should be enough for you to see what to do to add more.
Hi, I stubbled across this post and it is *exactly* what I have been looking for! Its great. One thing, how would I use the same cascading dropdown linked to my SQL database. I have the following.. SQL: Vehicle: Make: Model: Year: Product: Cheers Paul
For those wondering how to connect this with your database I have expanded on stoli's script here: http://www.khaoskreations.com/portfolio/hierselect.php It's a bit long, so I didn't want to copy and paste here. edit: And seeing as this is my first post I can't live link. >_> I've added a db call, a third tier and a new function 'reloadForm' for when the user needs to edit their selection. Hope this helps someone else like stoli's script helped me.
The above link has a live version of my script running, but here is the code: <?php /* Written for Khaoskreations 2010-06-13 */ //db connect code $query = "SELECT * FROM sample_people "; $result = mysql_query($query); //==============================================================================build arrays from db $last = array(); $first = array(); $dob = array(); if (!$result) echo "Error: ".mysql_error(); else { $last_group = ""; $first_group = ""; $num = mysql_num_rows($result); for ($i = 0;$i<$num;$i++) { $r = mysql_fetch_array($result); if ($r['last_name'] != $last_group) { $last[$r['last_name']] = $r['last_name']; $first[$r['last_name']][$r['first_name']] = $r['first_name']; $dob[$r['last_name']][$r['first_name']][$r['id']] = $r['dob']."::".$r['id']; $last_group = $r['last_name']; $first_group = $r['last_name']; } else if ($r['first_name'] != $first_group) { $first[$r['last_name']][$r['first_name']] = $r['first_name']; $dob[$r['last_name']][$r['first_name']][$r['id']] = $r['dob']."::".$r['id']; $first_group = $r['last_name']; } else { $dob[$r['last_name']][$r['first_name']][$r['id']] = $r['dob']."::".$r['id']; } } } //==============================================================================create scripts $script = "\n<script type='text/javascript'>\n"; //build last name array $script .= "var last_name = new Array("; $list = ""; foreach ($last as $key => $val) { $list .= " \"".$val."\","; //echo $val ."<br />"; } $list = substr($list, 0, -1); $list .= " );\n"; $script .= $list; $list = ""; //build first name array $script .= "\nvar first_name = new Array();"; foreach ($first as $lastn => $fary) { $list .= "\nfirst_name[\"".$lastn."\"] = new Array("; foreach ($fary as $key => $value) { $list .= " \"". $value . "\","; } $list = substr($list, 0, -1); $list .= " );"; } $script .= $list; $list = ""; //build dob array $list = "\nvar dob = new Array();"; foreach ($dob as $lastn => $fary) { $list .= "\ndob[\"".$lastn."\"] = new Array();"; foreach ($fary as $firstn => $aary) { $list .= "\ndob[\"".$lastn."\"][\"".$firstn."\"] = new Array("; foreach ($aary as $key => $value) { $list .= "new Array(".$key.", \"".$value."\"),"; } $list = substr($list, 0, -1); $list .= " );"; } } $script .= $list; //script functions to update tiers $script .= <<< EOSCRIPT function resetForm(theForm) { theForm.last_names.options[0] = new Option("Select...", ""); for (var i=0; i<last_name.length; i++) { theForm.last_names.options[i+1] = new Option(last_name[i], last_name[i]); } theForm.last_names.options[0].selected = true; theForm.first_names.options[0] = new Option("Select...", ""); theForm.first_names.options[0].selected = true; theForm.dob_id.options[0] = new Option("Select...", ""); theForm.dob_id.options[0].selected = true; document.getElementById("selectbox").innerHTML = ""; } function reloadForm(theForm,lastname,firstname,bday) { theForm.last_names.options[0] = new Option("Select...", ""); for (var i=0; i<last_name.length; i++) { theForm.last_names.options[i+1] = new Option(last_name[i], last_name[i]); if (lastname == last_name[i]) theForm.last_names.options[i+1].selected = true; } document.getElementById("selectbox").innerHTML = "here"; var fn = first_name[lastname]; theForm.first_names.options.length = 0; for (var i=0; i<fn.length; i++) { theForm.first_names.options[i] = new Option(fn[i], fn[i]); if (firstname == fn[i]) { theForm.first_names.options[i].selected = true; } } var dobs = dob[lastname][firstname]; theForm.dob_id.options.length = 0; for (var i=0; i<dobs.length; i++) { theForm.dob_id.options[i] = new Option(dobs[i][1], dobs[i][0]); if (bday == dobs[i][0]) { theForm.dob_id.options[i].selected = true; } } document.getElementById("selectbox").innerHTML = "You selected person #"+bday; } function updateFirstNames(theForm) { var lname = theForm.last_names.options[theForm.last_names.options.selectedIndex].value; var fnames = first_name[lname]; theForm.first_names.options.length = 0; for (var i=0; i<fnames.length; i++) { theForm.first_names.options[i] = new Option(fnames[i], fnames[i]); } var findex = theForm.first_names.options[theForm.first_names.options.selectedIndex].value; var dobs = dob[lname][findex]; theForm.dob_id.options.length = 0; for (var i=0; i<dobs.length; i++) { theForm.dob_id.options[i] = new Option(dobs[i][1], dobs[i][0]); } theForm.dob_id.options[0].selected = true; } function updateDOB(theForm) { var lname = theForm.last_names.options[theForm.last_names.options.selectedIndex].value; var findex = theForm.first_names.options[theForm.first_names.options.selectedIndex].value; var dobs = dob[lname][findex]; theForm.dob_id.options.length = 0; for (var i=0; i<dobs.length; i++) { theForm.dob_id.options[i] = new Option(dobs[i][1], dobs[i][0]); } theForm.dob_id.options[0].selected = true; } </script> EOSCRIPT; $reload_script = ""; if ($_POST['last_names'] != "" && $_POST['first_names'] != "") { $reload_script .= "<script type='text/javascript'> " ."reloadForm(document.peopleForm,'".$_POST['last_names']."','".$_POST['first_names']."',".$_POST['dob_id'].");" ."</script>"; } else { $reload_script .= "<script type='text/javascript'>" ."resetForm(document.peopleForm);" ."</script>"; } //============================================================================== build page $page = <<< EOPAGE <html> <head> {$script} </head> <body> <form method="post" action="hierselect.php" name='peopleForm'> <select name='last_names' onchange="updateFirstNames(this.form)"></select> <select name="first_names" onchange="updateDOB(this.form)"></select> <select name="dob_id"></select> <input type='button' value='Reset' onclick='resetForm(document.peopleForm)'/> <input type='submit' value='Reload'/> </form> <div id='selectbox'></div> {$reload_script} </body> </html> EOPAGE; echo $page; ?> PHP:
Hello, Many thanks for adding the code for this. I see its an old topic now, so hopefully you get this! I am using the code from the first post (as i know it works on my cms), but trying to figure out how to add a url to where each of the second menu items go when submitted. Would it be cheeky to ask you to add to the code for each of the models to open in the same page, lets say google.com. At the moment I am using multiple single drop-downs which isn't very user friendly. This is the code I use which when go is pressed takes you to the external url. <SCRIPT TYPE="text/javascript"> <!-- function dropdown(mySel) { var myWin, myVal; myVal = mySel.options[mySel.selectedIndex].value; if(myVal) { if(mySel.form.target)myWin = parent[mySel.form.target]; else myWin = window; if (! myWin) return true; myWin.location = myVal; } return false; } //--> </SCRIPT> <FORM ACTION="../cgi-bin/redirect.pl" METHOD=POST onSubmit="return dropdown(this.gourl)"> <SELECT NAME="gourl"> <OPTION VALUE="">Search Engines... <OPTION VALUE="http://www.google.com" >Google <OPTION VALUE="http://www.ask.com" >Ask </SELECT> <INPUT TYPE=SUBMIT VALUE="Go"> </FORM> PHP: Many Thanks, Tim
Hi There I used this code for my website, I replaced all the lastname, firstname, and dob references with the values in my table last_name = Make first_name = Model dob = Version I have also replaced all other values as references I cannot get the code to work, the boxes display, and if I view the source code, I see all the options are being gathered, but the dropdown boxes are not being populated, you can see this on http://www.carlightexpress.com/test2.php I want to replace the existing dropdown on my site to work with a single database and offer more granularity, which your script looks perfect for me to do so, just have this weird issue, I have attached the modified code, if you can tell me where I have gone wrong that would be great Thanks Simon
Sorted it, fantastic script, it works now with test3.php so all I need to do now is incorporate it and push the info through to a form, thanks a lot
I LOVE this example.one question, im having an error with one of the lines:if ($_POST['last_names'] != "" && $_POST['first_name'] != "") {this is what the error says:Undefined index: last_names in C:\xampp\htdocs\mixercenterpq\linda4.phpi tried to add my database field name but it didnt workthanks
I dont know what im doing wrong. my db names areMACHINE_TYPE instead of last_nameBRAND instead of first_nameMODEL instead of dob please let me know whats wrong, i dont understand why my boxes arent populatingmy url is mixercenterpq.com/linda4.php
I have a similar issue and I tried to incorporate the top Autos drop downs into my form but I can't get it to work. My code and info is at http://forums.digitalpoint.com/showthread.php?t=2609565#post18301821 Please help me out.