This example contains two select elements. When an item is selected in the first select, the choices in the other select are updated appropriately. The first select element contains a list of continents. The second select element will contain a partial list of countries located in the selected continent. There is an onchange event associated with the continent select. When the continent selection changes, the items in the country select are modified using JavaScript via the Document Object Model (DOM). All of the data required, the list of countries and continents, is included within the Web page.
Overview of the code below
countryLists array variable which contains the list of countries for each continent in the trigger select element.
countryChange() function which is called by the onchange event of the continent select element.
The XHTML code to create the select elements in the body of the Web page.
Example Code:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "//www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="//www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/xhtml; charset=utf-8" /> <title>Dynamic Select Statements</title> <script type="text/javascript"> //<![CDATA[ // array of possible countries in the same order as they appear in the country selection list var countryLists = new Array(4) countryLists["empty"] = ["Select a Country"]; countryLists["North America"] = ["Canada", "United States", "Mexico"]; countryLists["South America"] = ["Brazil", "Argentina", "Chile", "Ecuador"]; countryLists["Asia"] = ["Russia", "China", "Japan"]; countryLists["Europe"]= ["Britain", "France", "Spain", "Germany"]; /* CountryChange() is called from the onchange event of a select element. * param selectObj - the select object which fired the on change event. */ function countryChange(selectObj) { // get the index of the selected option var idx = selectObj.selectedIndex; // get the value of the selected option var which = selectObj.options[idx].value; // use the selected option value to retrieve the list of items from the countryLists array cList = countryLists[which]; // get the country select element via its known id var cSelect = document.getElementById("country"); // remove the current options from the country select var len=cSelect.options.length; while (cSelect.options.length > 0) { cSelect.remove(0); } var newOption; // create new options for (var i=0; i<cList.length; i++) { newOption = document.createElement("option"); newOption.value = cList[i]; // assumes option string and value are the same newOption.text=cList[i]; // add the new option try { cSelect.add(newOption); // this will fail in DOM browsers but is needed for IE } catch (e) { cSelect.appendChild(newOption); } } } //]]> </script> </head> <body> <noscript>This page requires JavaScript be available and enabled to function properly</noscript> <h2>Dynamic Select Statements</h2> <label for="continent">Select Continent</label> <select id="continent" onchange="countryChange(this);"> <option value="empty">Select a Continent</option> <option value="North America">North America</option> <option value="South America">South America</option> <option value="Asia">Asia</option> <option value="Europe">Europe</option> </select> <br/> <label for="country">Select a country</label> <select id="country"> <option value="0">Select a country</option> </select> </body> </html>Here is a working example: Dynamic Select
We can dynamically narrow down (or limit) the items in a second drop down list based on the selected item from first selected item.
For example if we have one list of countries in first drop down list and have list of states in the second list then
once USA is selected from the country list then the second list should change to list only the states of USA.
Two dependent list boxes showing options of second list box based on selection of first list box.
This cascading dropdown list box script is required in many places and there are two ways to handle such requirement. One is to get the full items list for both the drop down list to the client sides and manage by JavaScript and the other solution is submitting the form to the server on selection of first list and based on the selection get the element data for the second list. The first choice is advisable when we don't have many records for the second list and we can download all the data for the second list to client machine and handle it by using client side JavaScript. We will discuss the second solution as it is relevant to PHP MySQL section here and the first solution we will discuss in JavaScript drop down Tutorial section.
You can see similar solution of managing second drop down based on the first drop down in ASP using VBScript
Demo and sample scripts to download
Two Dropdown list | Linked drop down list using PHP MySQL |
Three Dropdown list | Three Linked dropdown list |
Using PHP & AJax to manage dropdown list box
Two Dropdown list | Without reloading the page by using Ajax |
Two Dropdown list | Linking Multiple selection of dropdown list with Second list box |
Three Dropdown list | Three list boxes for Country, State & City using Ajax |
Other tutorials on Dropdown Listbox
Disable list | Enabling second list box after selection of first list |
FAQ on Dropdown list | Some solutions in installation and troubleshooting the script |
List Table | Populating options of dropdown list box by taking data from table |
List Period | Linking a listbox options to a radio button selection |
Using jQuery
It became very easy to manage and modify the script if you are using JQuery. Today most of the sites uses JQuery for better user experience. Here are some tutorials with Demo for managing dropdown list box using Jquery. Here also we have used PHP and backend script and MySQL as database.Two Dropdown list | Interlinked two dropdown list using JQuery |
Three Dropdown list | Interlinked Country > State > City List box using JQuery |
Two tables created in MySQL database for populating the data in the drop down lists. One is category table and other one is subcategory table. Both tables are linked by the field cat_id. The data taken for this example is common data of fruits, games, vehicles, colors used as category and corresponding values are taken as subcategory.
The first table is populated in the first drop down list by taking directly from the table without any conditions in sql statement. In case of second drop down list the presence of variable having the value of category is checked and if the category number is present then the sql is changed to add one condition in where clause. The variable to second list query is passed by submitting the form to itself when any value is selected in the first drop down list. We will be using the onchange event of the select element to submit the form.
We will write one function in JavaScript to handle the onchange event of the first drop down list box. We will keep this function inside our head tag. Once the element in first list gets selected it will call the function and the function will add the selected item to the query string and will reload the page. So for the second drop down list the variable will be available. <SCRIPT language=JavaScript>
function reload(form){
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='dd.php?cat=' + val ;
}
</script>
Please note that we have used dd.php as our file name. In your case change the file name. Now let us first prepare the Query for the first drop down list by getting the data from the category table. $query2="SELECT DISTINCT category,cat_id FROM category order by category"; With this query we can populate the first drop down list. This is a simple solution but for the second drop down list we will check the presence of selected item of first drop down list. If it is present then we will restrict our records to that category only other wise we will collect all the records for the second list. To know how the WHERE query works, you can visit our sql section. Here is the code to do this. Watch the if condition.
As we are using variables taken from query string and using them inside our query, we must sanitize the variable before use for any malicious code or query which hackers can use. As we know our cat_id will have only numeric data so we will use is_numeric function to check the variable. You can read more on sql security here. $cat=$_GET['cat']; //This line is added to take care if your global variable is off if(strlen($cat) > 0 and !is_numeric($cat)){//check if $cat is numeric data or not. echo "Data Error"; exit; } This way we can control the data of the second list. Now the form part we will work. See how the onchange event is used ( onchange=\"reload(this.form)\" ) inside the select command. This will execute the function reload and will submit the selected item to the page again by using the query string.
MYSQLI & PDO to manage Database
Here in this example code we used MYSQLI functions to connect and manage MySQL database. In your downloaded ZIP file you will get different DEMO pages using with both MYSQLI and PDO to handle databaseHere is the code. $cat=$_GET['cat']; // This line is added to take care if your global variable is off if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not. echo "Data Error"; exit; } ///////// Getting the data from Mysql table for first list box////////// $query2="SELECT DISTINCT category,cat_id FROM category order by category"; ///////////// End of query for first list box//////////// echo "<form method=post name=f1 action='dd-check.php'>"; ////////// Starting of first drop downlist ///////// echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>"; if($stmt = $connection->query("$query2")){ while ($row2 = $stmt->fetch_assoc()) { if($row2['cat_id']==@$cat){echo "<option selected value='$row2[cat_id]'>$row2[category]</option>";} else{echo "<option value='$row2[cat_id]'>$row2[category]</option>";} } }else{ echo $connection->error; } echo "</select>"; ////////////////// This will end the first drop down list /////////// ////////////////// Second drop downl list ////////// echo "<select name='subcat'><option value=''>Select one</option>"; if(isset($cat) and strlen($cat) > 0){ if($stmt = $connection->prepare("SELECT DISTINCT subcategory FROM subcategory where cat_id=? order by subcategory")){ $stmt->bind_param('i',$cat); $stmt->execute(); $result = $stmt->get_result(); while ($row1 = $result->fetch_assoc()) { echo "<option value='$row1[subcategory]'>$row1[subcategory]</option>"; } }else{ echo $connection->error; } ///////// }else{ /////// $query="SELECT DISTINCT subcategory FROM subcategory order by subcategory"; if($stmt = $connection->query("$query")){ while ($row1 = $stmt->fetch_assoc()) { echo "<option value='$row1[subcategory]'>$row1[subcategory]</option>"; } }else{ echo $connection->error; } } ////////// end of query for second subcategory drop down list box /////////////////////////// echo "</select>"; ////////////////// This will end the second drop down list /////////// echo "<input type=submit value='Submit'></form>"; If you are facing any problem in using this code, please post it in php discussion forum with your error messages, bugs etc. .. Dropdown list without reloading the page by using Ajax & PHP
More on PHP Drop down list tutorials with Demo
Haki | 03-07-2012 |
Hi, Thanks for your great codes. How can I modify this drop down code so that instead of (or in addition to) displaying the results, it posts the results into a new table? I would greatly appreciate such a wonderful solution. Thanks |
Amani Musomba | 15-09-2012 |
I got this one to work for the whole form thanks for that, how do I do If I want to reload/refresh only the fields and not the whole form? the form is having some other fields that I do not need them to be updated when the user chooses to update these two fields. |
ali | 15-09-2012 |
Thanks for your great codes. How can I modify this drop down code so that instead of (or in addition to) displaying the results, it posts the results into a new table? I would greatly appreciate such a wonderful solution. Thanks |
smo | 19-09-2012 |
You need to have all the connection to mysql and then develop a query to insert into table. Must have PHP and MySQL knowledge |
AJSP | 14-10-2012 |
can u explain me what is $cat whether it is database name? |
Stelios | 19-11-2012 |
I want help to develop this code. The problem is that after selection of the second drop down list I would like to copy the selected item to the input type text field at the same page without a submit input type; like the example with the three level drop down (but without reload page). I will be grateful for your help |
Larry | 28-11-2012 |
I am needing the same help that Stelios is asking. |
Karthik | 07-03-2013 |
HI, Thanks for the great code posted. How can we modify the code so that field type can be "Text/Varchar" instead of "INT". Also is it possible to run code with only one table, than using 2 tables?? Please let me know. |
saman | 01-08-2013 |
hi, i cant narrow down the values of the second one right now ive got all the values in the category dropdwon and all the subcategories appearing in the 2nd dropd when i select one category the form reloads and i get the actual cat value to appear on the url so that selection is made but the <selection>category name becomes"Select One" in the category dropd and the values of subcategory are not narroed down to the selection any thoughts |
Utkarsh Shinde | 05-08-2013 |
if dropdown is multi selectable than how to do this. |
Farukh Khan | 21-10-2013 |
Thanks for your code. it realy helpful for me :) |
smo | 24-10-2013 |
For Multi select-able drop down list we can send a set of selection to query sting . To do this you can refer to JavaScript multi selection tutorial. Next step is to modify the query by using IN clause to collect matching records. |
smo | 27-10-2013 |
One demo with multi select drop down list is added. You can download the zip file to get the code of single and multi select-able drop down list |
karthik | 12-11-2013 |
Hi , I want page submit without reload the page and also need to display same page. Thanks! |
pawan kumar | 13-11-2013 |
Hi, Thanks for your great codes. How can I modify this drop down code so that instead of (or in addition to) displaying the results, it posts the results into a new table? I would greatly appreciate such a wonderful solution. Thanks |
yogesh | 02-05-2014 |
Hi,Thanks for plus2net for giving support by providing valuable code. I downloaded aiax-dd3 folder for dropdowns. I am not getting where to modify for adding another dropdown i.e.four dropdowns i nedded but here it consist only three dropdowns.Thanks |
raj | 03-06-2014 |
Hi, I want to retain the ajax selected values in the respective text fields after submit button. Can u help in this regard. please send me a mail Regards |
Angel | 10-06-2014 |
Hi great work on this. Thank you. But I have a question? For updating records in the database, how to retrieve a value in database and preselected in the dropdown list. |
spiro2903 | 12-06-2014 |
Would it be possible to do this where 2nd menu is populated by column values from selected row? For example: Option1 | A | B | C Option2 | 1 | 2 | 3 First menu would be Option1/Option2 and based on choice 2nd menu would be ABC or 123. |
Mehul Patel | 20-09-2014 |
Can you help me with this option 01 - "SUV car" , "Hatch Back Car" , "Sports car" option 02 - "Prado SUV" , "safari SUV" , "Swift Hatchback" , "Fabia Hatchback" , "Ferrari Sports" , "aston martin Sports" Option 03 - "red prado" , "Green Prado" ,"red safari" , "green Safari" , "red swift" , "green Swift" , "red fabia" , "green fabia" , "red Ferrari", "green Ferrari", "red aston martin" , "green aston martin" hope you can understand what m trying to explain, |
Mahesh | 01-11-2014 |
Hi, Can anyone help me to use this code as wordpress plugin.Thanks in advance. |
pat | 05-12-2014 |
How can we modify the code so that field type can be "Text/Varchar" instead of "INT?". Thanks! |
rie | 09-01-2015 |
i will ask, instead of listbox in the second listbox, i will change it to textbox so that when i select the 1st listbox the 2nd info will appear in textbox ... can anyone help me .. Thanks in advance..!! |
rie | 09-01-2015 |
not like that sir, sorry its hard for me to explain very well... what i mean is, like the two dropdown but in this case, 1 listbox for the category & 1 textbox in subcategory.. when i select the category in listbox, the subcategory will appear in textbox instead.. Thanks in advance ..!! :) |
smo | 09-01-2015 |
2nd dropdown displays multiple option but you want to display them in a textbox then you can change the section saying //// starting of second dropdown //// Here collect the matching data and place them inside textbox value <input type=text name=t2 value='$noticia[subcategory]'> Note that here inside the loop it will display multiple textbox with different subcategory value. You can create a string by adding them and display one common string if you want only one textbox to display. |
rie | 09-01-2015 |
it works, thanks sir smo.. Godbless You..!! |
rie | 09-01-2015 |
nxt question in my previous pending part of my project .. 2 dropdown menu, when i use numeric only in 1st dropdown it works, but if i use alphanumeric no subcategory will appear. help me please, Thanks in advance ..!! |
pat | 12-01-2015 |
can anyone help me on how to insert data into a table, i think this is a pdo.. dont have any idea about pdo .. thanks in advance! |
Josh | 03-04-2015 |
Hello Please can anyone help me . I want to modify the code to display 5 dropdowns. Any advice will be appreciated. Thanks |
smo | 06-04-2015 |
Going for 5 dropdown using this is bit complex. Better to use jQuery for this. Shortly we will be adding that part. You can see some examples in jQuery section. |
Meri | 05-04-2016 |
thanks to you buddy ..... it helps a lot!!! |
ROHIT | 06-12-2016 |
hello sir your code is working well but i facing little bit problem for inserting that value which i selected in both drop-down value. what i want is my both value should be inserted in another table but happen in your code i its taking value only first drop-down box and inserting same value in both table there is any solution plz help me. thank you |
praveen | 26-12-2016 |
I have four select list box. depending upon the one selection from first list box.It should filter the other list box also depending on selection of first list box.Once you select first list box value. I am having one button called generate report. The report must contain all the values related to one selection from first list box other list box should be filtered based on first select box.the second select box which has filtered depends upon the first box (actually this is chained select drop down list).The report must contain all the values from first select drop down list and also generate report all filtered related values for the first generate report button and so on for four chained select drop down list. How go about it? |
smo1234 | 30-12-2016 |
Better to use JQuery for this. Once you select one option of first drop down, details ( report ) of the option is displayed ( no need to press any button ), at the same time it selects the options of 2nd list. This can continue for all other drop down also. You can combine reports of selected drop down boxes or can show only the recent selected option. You can check the demo of three dropdown list using JQuery |
renuka | 19-04-2017 |
what if i want to take option values from same table only? please help |
smo1234 | 02-05-2017 |
Same table or different table can be used for data population as options for the drop down list. |