SQL PHP HTML ASP JavaScript articles and free scripts to download
PHP Download Script

Dynamic populating the drop down list based on the selected value of first list

How to 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.

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

Demo Description
Two Dropdown listLinked drop down list using PHP MySQL
Three Dropdown listThree Linked dropdown list

Using PHP & AJax to manage dropdown list box

Demo Description
Two Dropdown listWithout reloading the page by using Ajax
Two Dropdown listLinking Multiple selection of dropdown list with Second list box
Three Dropdown listThree list boxes for Country, State & City using Ajax

Other tutorials on Dropdown Listbox

Tutorial Description
Disable listEnabling second list box after selection of first list
FAQ on Dropdown listSome solutions in installation and troubleshooting the script
List TablePopulating options of dropdown list box by taking data from table
List PeriodLinking a listbox options to a radio button selection
Please note that the all solutions require JavaScript client side support so it is better to check the JavaScript status for the client browser.

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 sql for the first drop down list by getting the data from the category table.

$quer2=mysql_query("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 sql 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;
}
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory";
}else{$quer="SELECT DISTINCT subcategory FROM subcategory order by subcategory"; }

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. Here is the code.

echo "<form method=post name=f1 action=''>";
/// Add your form processing page address to action in above line. Example action=dd-check.php////
////////// Starting of first drop downlist /////////
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['cat_id']==@$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";

////////////////// This will end the first drop down list ///////////

////////// Starting of second drop downlist /////////
echo "<select name='subcat'><option value=''>Select one</option>";
foreach ($dbo->query($quer) as $noticia) { {
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
////////////////// This will end the second drop down list ///////////
// add your other form fields here ////
echo "<input type=submit value=Submit>";
echo "</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

download script

Number of User Comments : 21


Google+
Haki03-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 Musomba15-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.
ali15-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
smo19-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
AJSP14-10-2012
can u explain me what is $cat whether it is database name?
Stelios19-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
Larry28-11-2012
I am needing the same help that Stelios is asking.
Karthik07-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.
saman01-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 category name becomes"Select One" in the category dropd and the values of subcategory are not narroed down to the selection





any thoughts
Utkarsh Shinde05-08-2013
if dropdown is multi selectable than how to do this.
Farukh Khan21-10-2013
Thanks for your code. it realy helpful for me :)
smo24-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.
smo27-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
karthik12-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
yogesh02-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

raj03-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
Angel10-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.
spiro290312-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.
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked



Join Our Email List
Email:  
For Email Newsletters you can trust
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer