How to create chained select with PHP and jQuery?
In this article we’ll talk about the chaining of select also called select cascade.
It is a procedure that we often find on the web and it consists in giving the user the possibility to find a specific data through a few passages: practically choosing a category in the first select, the second one will be populated with the results related with the category selected.
We imagine, for example, a first select where it is possible to choose between motorcycles and cars; once we selected the car category , the second select will be populated with the brands of the cars available. Then selecting a brand, the third select will be populated with the models available of this brand. In this article we’ll see a very simple example but it will give us the basis to comprehend the procedure to do even in the case of more complicated cascades.
You can examine what we will create in this page of example. I state in advance that the argument is quite advanced and it presumes a medium-advance level of knowledge of PHP and of MySql.
As you can see, the example is very minimalist. A first select that requests the category in which appear: colours, flowers and tools. A second select in which once the category is selected we’ll find a list of items concerning that category.
Create the structure of the database
So we are going to create a table called categories with the fields
- id_cat
- name
And another table called type with the following fields
- id_type
- id_cat
- name
This way we can determine the correct relation between the tables.

Therefore create the database selectExample and execute the query that I prepared to help you out in this task. Besides creating the tables necessary , it inserts the data we need for the exercise.
CREATE TABLE `categories` ( `id_cat` int(4) unsigned NOT NULL auto_increment, `name` varchar(40) NOT NULL, PRIMARY KEY (`id_cat`) ) ENGINE=MyISAM AUTO_INCREMENT=4 ; INSERT INTO `categories` (`id_cat`, `name`) VALUES (1, 'colours'), (2, 'flowers'), (3, 'tools'); CREATE TABLE `type` ( `id_type` int(4) unsigned NOT NULL auto_increment, `id_cat` int(4) unsigned NOT NULL, `name` varchar(40) NOT NULL, PRIMARY KEY (`id_type`) ) ENGINE=MyISAM AUTO_INCREMENT=15 ; INSERT INTO `type` (`id_type`, `id_cat`, `name`) VALUES (1, 1, 'yellow'), (2, 1, 'green'), (3, 1, 'red'), (4, 1, 'gray'), (5, 1, 'white'), (6, 2, 'daisy'), (7, 2, 'cowslip'), (8, 2, 'lily'), (9, 2, 'sunflower'), (10, 3, 'hammer'), (11, 3, 'screwdriver'), (12, 3, 'spatula'), (13, 3, 'wrench'), (14, 3, 'clamp');
Preparation of the main page
Now let’s prepare the main file that is select.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
</script>
</head>
<body>
<form id="select_form">
Choose a category:<br />
<select id="category">
</select>
<br /><br />
choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
</body>
</html>
As you can see I included jQuery. In fact thanks to an ajax call we’ll populate the second select.
I declared a form containing the first select with no option and the second select containing only an option that is “choose…”. Then we have an element with id result in which at the end we’ll insert the choice made.
Create the file with the parameters of connection
Now we create the file db_config.php that will contain the parameters of connection to the database.
<?php $host = "localhost"; $user = "root"; $password = "*********"; $db = "selectExample"; ?>
Naturally you have to assign the parameters of your database.
The php file for the management of the requests
At this point we start creating the PHP class that will handle the elaboration of the information and will give back results. The file will be called select.class.php.
class SelectList
{
protected $conn;
public function __construct()
{
}
}
We begin with declaring the class, afterwards the propriety $conn that will contain the connection resource to the database and at the end the builder method, that at the moment we leave empty.
Now we write the method for the connection to the database.
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
As you see, after I included the parameters I proceed with the connection and therefore with the selection of the database.
Now we proceed with the creation of the ShowCategory() method that will create the option of the first select. This method will be executed directly with the page load, we’ll see how afterwards.
public function ShowCategory()
{
$sql = "SELECT * FROM category";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . '">' . $row['name'] . '</option>';
}
return $category;
}
As you can see I execute a query that selects all the lines of the category table. Afterwards I insert in the variable $category the first option, containing a message that invites the user to make a choice. At the end I add at the variable $category as many option as the items present in the table, being sure to indicate as value the id of the category and as contents of the tag option the name of the category.
Now let’s write the last method that will fetch the value passed from the first select (the id of the category) and will populate the second according to the value passed from the first.
public function ShowType()
{
$sql = "SELECT * FROM type WHERE id_cat=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['id_type'] . '">' . $row['name'] . '</option>';
}
return $type;
}
In this case through the query we’ll select the lines of the type table that have as id_cat the value passed through POST (this value will be passed with an ajax call, but we haven’t written it yet, we’ll see it after).
The rest is similar to the previous method.
Now, considering that whatever operation does this class it is necessary the connection to the database, we can invoke the method DbConnect() directly in the constructor method.
Moreover we can, for convenience, instantiate the class directly in this file.
So here the whole class:
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowCategory()
{
$sql = "SELECT * FROM category";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . '">' . $row['name'] . '</option>';
}
return $category;
}
public function ShowType()
{
$sql = "SELECT * FROM type WHERE id_cat=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['id_type'] . '">' . $row['name'] . '</option>';
}
return $type;
}
}
$opt = new SelectList();
?>
Now let’s go back to work on the main file (select.php)
From the moment that this file will be loaded the first select has be populated. We’ll do it inserting the method ShowCategory() in this way:
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
As you see, we include the class already instantiated in the object $opt. Afterwards, between the tag select, we print the result of the ShowCategory() method, that will be the option correctly populated with the values taken from the database.
You can try the script and see that the first select will populate correctly.
Implement the ajax functionalities
Now, what we have to do through jQuery is to fetch what will be selected in this select and send the data (the id of the category) to the method ShowType() that will return us the option to insert in the second select. Everything naturally with an ajax call. The code (like always with jQuery is very simple) is the following (that goes inserted in the function $(document).ready).
$("select#category").change(function(){
var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").html(data);
});
});
What does this mean? At the occurence of change in the select with id categorie, execute this function that:
- Enhances the variable id with the attribute value of the option selected.
- Sends through POST the variable id to the file select_type.php (that we haven’t written yet, but we’ll do it immediately).
- What is returned from this call insert it in the select with id type.
Create a service file
Obviously the file select_type.php will be a service file that will simply invoke the method ShowType().
<?php include "select.class.php"; echo $opt->ShowType(); ?>
At this point you can try the script. Now selecting a category, the second select will get populated correctly.
Improve the usability
Now let’s add something else. Do you remember the question on the usabilty faced in the previous article on ajax? Good, I think that the second select should be disabled when the page gets loaded. At the beginning of the call we could replace “select” with “wait…”. Once the call has been executed, the select can be enabled. This is correct under the point of view of the usability. Therefore we modify the code in this way:
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>");
var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
Now all we have to is determine what happens when you press enter . In our case we’ll write the choice made in the element #result. WE should also consider (usability) what happens if the enter button gets pushed before all the choices have been made.
This is the code that I will explain later.
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
At the occurrence of submit, we take the value of the attribute value of the two select. If these values are both greater than zero (therefore a choice in the select has been made in the two select), we take the contents of the select with id type and we print it in the element #result.
Instead if the two choices haven’t been made, in the element #result we print the error message.
Here select.php complete with all the changes.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>");
var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
</body>
</html>
Conclusion
In this article we saw an application of ajax very useful and requested. Considering that it’s an advanced functionality it’s obvious that it can seem complicated for those who don’t have a certain mastery of php, on the other hand it cannot be made more simplier than this.
However we need to say that for a correct application of the criterions of accessibility, we should foresee a solution that allows the use of this system, even without the use of javascript (and therefore of jQuery).
And you, what do you think about it? Did you find this article too complicated? Will you use these principles in your sites?
*****************************************
L'immagine principale dell'articolo è stata fornita da @Fotolia
83 comments
Trackback e pingback
-
Tweets that mention How to create chained select with PHP and jQuery? | Your Inspiration Web -- Topsy.com
[...] This post was mentioned on Twitter by soshableweb, mtx_maurizio and V. Tavares (E-Goi), Tom Bangham. Tom Bangham said: How ... -
You are now listed on FAQPAL
How to create chained select with PHP and jQuery?... In this article we'll talk about the chaining of select also called ... -
20 jQuery Tutorials of Any Complexity Level | Agnis Designers
[...] 10. How to create chained select with PHP and jQuery [...] -
Chained Select with PHP and jQuery « Jquery Labs
[...] Tutorial Tutorial Page [...] -
PHP, Ajax, MySql, Javascript Chain Select | Jagadishwor | Ajax, jQuery, PHP MySql Tutorial Tips and Tricks
[...] Your Inspiration Web (PHP [...] -
Fresh jQuery Plugins For Your Next Project - Episode 7
[...] Demo Download [...] -
Element with jquery |Avnish Namdev
[...] How to create chained select with PHP and jQuery? [...] -
PHP Dynamic Checkbox List from SQL, based on Cascade Select selection | Code and Programming
[...] I came across this tutorial, pretty much what I wanted and I worked on the database based on this: ...



This script is not working in FF
first drop down box is not listing ….
can you update me i had just copied all the files but not working….
Correction – This script is working perfectly in FF, IE8 and Chrome
You might spot an error or two which have been pointed out below, namely a small mix up of using “categories” in the db and “category” in the script.
You would also need to edit so you have the correct jQuery version…
Other than that – all works perfectly.
The Worst PHP tut I’ve ever seen
This statement is just ridiculous… You couldn’t get it to work so you criticize.
I personally would say that some of the English is a little scatty, sorry to author…
But the main thing is that the script is (almost) flawless and works perfectly if you take your time and learn to walk before you try to run, programmatically speaking.
Thanks very much to the author, you don’t deserve such non-sense replies from people who simply don’t yet possess the skills to make your fine script work.
One more thing can you please start a series like
PHP for ABSOLUTE Beginners.
Thanks for great tutorial.
Is it posibile, and how, to save all chosen to the database.
Great tutorial!!
but when i put these dropdowns in a form and submit, second dropdown doesn’t included.
i am new to programming, so can’t trace out why it does so.
any help will be highly appreciated
>> Jack.
Yes I was able to figure it out. Let me know what your email is and I will send you my scripts for third drop down box.
-Chris
Great demo! Could you possibly show how to add a third select menu?
I am having some difficulties figuring it out.
Thank you,
Hi,
Great tut !
I have a problem to populate the second dropdown menu. The first show correctly, but the second nevers show the content asked from the first, it is still greyed and disabled.
An idea ?
Regards
Hi Chris, I have the same question. Did you get an answer? I’ve gone to Maurizio’s website and I don’t read the language. Any help would be appreciated.
Jack
Chris – to clarify my earlier email – you wrote “Could you possibly show how to add a third select menu?” Any help on that question?
Thanks Jack
Hard to tell without seeing what your code looks like.
I just tested your ajax chained select and is working fine. The only problem is how and why is the ajax pre-fetching the second select option even before the first select option was selected.
Though it doesn’t show up in the select but looking at the page source at page load, you will see all the data for the second option in the source? It’s like it’s doing the filtering in the page, if so what’s the purpose of the ajax?
Secondly, i am also wondering which id is being sent to the second option select datapage query page because on page load, all data from second option table is loaded so it’s kind of bye passing my WHERE clause which i don’t know why because only records matching _POST['id'] should be selected but everything is being selected, how come i cant say.
Any ideas
To answer the first part of the question, it doesn’t seem you have it set up correctly. For the second portion of your question. Use firebug. It is a firefox add-on and it will show you what parameters are being sent via HTTP requests.
HTH,
Chris
or Php Jump Recorder
We Need Jquery Selectbox..
http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/selectboxes/jquery.selectboxes.js?r=6185
Only Work class=”jumpmenu” Selectboxes
—
$(“.jumpmenu”).change(function() {
var val = $(this).selectedValues();
if (val != ”) {
location.href = val;
}
})
—
Select Class
—
public function ShowType() {
$sql = “SELECT * FROM arabalar WHERE b_id = $_POST[id]“;
$res = mysql_query($sql, $this->conn);
$type = ‘Choose…’;
while($row = mysql_fetch_array($res)) {
$type .= ” . $row['a_adi'] . ”;
}
return $type;
}
—
HTML
—
Choose…
Hello,
Can you tell me how should I modify the code (the jQuery part) in order to integrate it in a Joomla module?
Best regards,
Mihai
Hi Chris,
My email is jack@charter.net. I appreciate your help with the 3rd drop down!
Good demo and also useful.But this stuff are a bit hard for me,maybe I should learn more.
Hi All,
The double dropdown is working great. Thanks for it! I have been able to adapt it to a registration page for my db. My challenge is when I send to INSERT the information from the dropdowns, it is being accepted and creating a new row on my table – the only thing is the info being generated by the dropdowns is being added as ID#s not “names” into the new row.
For example, when I select (highlite) “Tennesssee” in the ‘state dropdown’ it puts it into my new table row as “37″ not Tennessee). How can I make the dropdown “selected” name be the “name” and not the ID# sent to the db with the INSERT command? It does the same on the other dropdown as well. Any help would be appreciated.
Dear Sir,
Please Help Me!
How to create chained select with PHP and jQuery?
I need jquery-1.3.2.js and jquery-1.4.1.js file for this script.
No, only one
Just download it from http://jquery.com/
Great tut. Only issue I found was small error. in select.class.php you have:
$sql = “SELECT * FROM category”;
should be
$sql = “SELECT * FROM categories”;
for this example
Preciso de ajuda, nao estou conseguindo enviar vai post para a proxima pagina o meu segundo select(diretor), pode ajudar? enviando script.
Sistema de Controle de Compras
Login Sistema de Compras
Login:
Senha:
Supervisão ou Gerência:
<form action="” method=”POST” >
<input type="hidden" name="email_super" value="”>
<input type="hidden" name="nome_super" value="”>
Escolha o Supervisor
query($sql);
$total = mysql_num_rows($db->res);
if ($total>0){
for ($i=0;$ile_linha();
// echo “$linha[id_email] , $linha[nome_super] , $linha[email_super],$linha[ccusto] “;
?>
<option value=>
<form action="” method=”POST”>
<input type="hidden" name="diretor" value="”>
Diretor:
Escolha o Diretor
Andre
Giorgia Pires Ferreira
Zilmino Tartari
<input type="hidden" name="diretor" value="”>
libera_result();
?>
Hello Maurizio.
Thank you for this wonderfull tool, as someone already asked you, I would like to have also the code to make it work with a 3rd select box.
I apreciate your help. My email is alfredo0655 at hotmail dot com.
Thanks in advance.
Good job, its great tutor for me
Thanks for this one
hi… can anyone tell how to implement 3rd level drop down menu?
Chris, great tutorial! Could you email me on how to implement third dropdown? info @ fishermanresource DOT com
very handful piece of code!!
by the way for those who are using the exact code, there is an error on the ShowCategory() method
the actual table is calle categories so the query should be SELECT * FROM categories
domenico can you upload these files somewhere???my script does not work…
THANK YOU!!!!
I would also greatly appreciate info on more than 2 dropdowns, I have a need for 4. 1 category and 3 types.
Thanks for the great tutorial also!
macri at mymcs dot us
for 3 drop down selects email reaperz0@yahoo.com
Hello
Thanks for your great script, but there is a problem
After changing the mistake with the category instead of categories the second menu show nothing…only the first…why???can you upload somewhere all these files??
Thank you very much
I see that several people found the “categories” error in the first SELECT statement (select.class.php) and that several people were still not able to get the second drop-down to work. I cut&past the code for this tutorial into my textwrangler so I know I didn’t make any keying errors. Is there another error I missed? Something that still needed correcting. I am self taught and don’t always use the correct terminology but I am sure, with a little push in the right direction, I will get this figured out. Any help would be greatly appreciated.
Jenna,
it didnCreate a service file
Obviously the file select_type.php will be a service file that will simply invoke the method ShowType().
?
ShowType();
?>
At this point you can try the script. Now selecting a category, the second select will get populated correctly.
thank you
Very nice tutorial, you sir deserve a medal! Thank you very much.
I really liked these tips jquery and php, I think the post was very enlightening and will help me in future projects. Thank you.
Please send source for three chained selects.
I have the original working for my tables, but want to add a third.
Your email address reaperz0@yahoo.com got returned
Hello,
Thank you for this script.
After installation and adjustment ‘categories’ my first list displays correctly and after selecting one of the options, my second list is empty.
Databases exist and are not empty.
Do you have any idea?
Good day.
PS: Excuse my bad english.
Hello,
I found my mistake. It was the closing PHP was poorly done.
But thank you anyway.
Good day.
Can you be more specific please, Heaven?
I’m new to this, and I cannot see an error in the select.class.php (or the select.php) file.
My first box populates since I changed the “category” to “categories” in “select.class.php”, but the second box does not populate after I have made my choice in the the first box.
I have tried changing:
Next…
to:
ShowType(); ?>
but that wasn’t the answer.
Andy.
Please lem me know what you did. I have the same issue.
Great tutorial
Please send your three chained selects if it is available.
Thanks in advance.
PS. My changes are minimal because I use the “as” function in the Selects, but I have them working for a couple of situations.
Thanks again
Thank You. It was very helpful.
Hi can I get any help?..I am having an error with this line ” $sql = “SELECT * FROM type WHERE id_cat=$_POST[id]“;”. I get the error “undefined index id”
great tutorial
Take this, Jquery Chained could be a better solution for you all. It does the hard job for you
http://www.appelsiini.net/projects/chained
That’s quite cool, Mauronimo!
What interests me about Marco’s solution though, is the calls from a database.
I want to call items from a MySQL database that includes around 9000 products in 10 categories, with dozens of subcategories! I want my buyers to be able to select a product in around 3 clicks.
I will be using your link for other applications though, for sure! Thank you.
Andy.
OK, I was a numpty, and it was late… amazing what a fresh pair of eyes after some sleep can do.
For those new to this, and struggling a little, here is a link to working code. (In a .RAR file.) I hope I’m not breaking any rules here (the code is EXACTLY as Marco intended, with the “categories/category” spelling mistake corrected, but I have put the .JS and “included” files in their own folders.)
http:// kandholhu dot com / chained-select dot rar
I hope this helps other newbies, such as myself.
It’s a great tutorial, hampered slightly possibly by language differences and the way a coder thinks when writing! What’s clear to someone writing isn’t always clear to those reading.
Andy.
PS. Thank you Marco, I have already learned something from your post, and I am now confident about a 3-level (or more) dynamic chained select process via database calls!
he Worst PHP tut I’ve ever seen
Thanks for the tutorial! After searching and trying to implement several other chain select scripts this one did the job perfect. Cheers
Hello sir,
I have modified code and everything was ok, but my second combobox doesnot populate after I choose something in first combobox. Please help me.
I cant seem to get the second list to populate… I’ve been at it for some time and believe the issue has something to do with the jquery (with which I’m inexperienced). Anyone care to explain the process of editing the jquery version in a little more detail?
Thank you so much, I am a very much new to jQuery with Ajax functionality and I was searching so many tutorial for drop down to add in my project but this tutorial is amazing. It clear all of my doubt and now I think i can create my own program wit jQuery and Ajax yes offcourse php and mysql. I am thanking you again for such a wonderful tutorial.. keep it up …
Hi.
I’m trying to adapt your code but no way. On change the second select option get empty. Several days trying to find how.
In my case I have a class for the first select and another for the second, but both of them returns the same string as yours.
If you have some time to take a look to my code, my email is: davisoski@gmail.com
Thanks
David, I’ve e-mailed you (and “Miha3la”) a copy of my code. Please feel free to share it with others, as I don’t have oodles of time to support someone else’s blog, but like to help where I can.
It’s a good tutorial, but it does need some refining! There are a couple of mistakes in the author’s code, and some bits “left to the reader’s imagination”… it’s certainly not for total newbies, in my opinion.
It does explain what each step is doing, and is very helpful, but you have to work at the sample code.
Andy.
Dont use it. Its not safe.
Something like that :
$sql = “SELECT * FROM type WHERE id_cat=$_POST[id]“;
will allow anyone to drop your database (delete)
Thanks for the great tutorial chris. Kindly send me the three chained select. my email is hezron.apunza@gmail.com
Thanks
hy,
it is great script, all is working fine, but for my project i need some adjustments
first a question: can i invoke the method ShowType() from the same page where i have the form?
this is why:
my connection settings (the database), and other params, used in the chained select can be changed, so I need to have all the script in one page.
it works until I transmit the “ID”
$(“select#mod_cal”).attr(“disabled”,”disabled”);
$(“select#ser_rep”).change(function(){
$(“select#mod_cal”).attr(“disabled”,”disabled”);
$(“select#mod_cal”).html(“wait…”);
var id = $(“select#ser_rep option:selected”).attr(‘value’);
$.post(“form-page.php”, {id:id}, function(data){
$(“select#mod_cal”).removeAttr(“disabled”);
$(“select#mod_cal”).html(data);
});
});
and afther that the second select is not populated
Czas: 2013-01-10 13:26:26
Błąd: TypeError: $(…) is null
WTF???????!!!!
is it possible to put the result of function ShowType() in a input field?
Hi Chris!
Nice tutorial! Kindly send me the three chained select. My email is f.pecher@coopdesign.de
Thank you!
Hi Cris.. great tutorial.. but do you have any other tutorial that involves multiple selects(more than 2) like this site http://travel.2go.com.ph/index.asp … please email me @ jehaneng@gmail.com.. tnx..
Hi sir!
Why is it after the 1st option is selected the 2nd option wont load? I am new to this please help me figure this out.
Alot of thanks to someone who can help me pls pls pls.
bravo!
Can anybody tell me which code exactly gets the id from categories in order to populate the types?? Trying to understand how jquery works…
Hi Noella,
I hope the below details may help you in understand better.
Html to display the Category:
Choose a category:
ShowCategory(); ?>
Below code is the one who is displaying the category id and value.
/* PHP FUNCTION */
public function ShowCategory()
{
$sql = “SELECT * FROM category”;
$res = mysql_query($sql,$this->conn);
$category = ‘choose…’;
while($row = mysql_fetch_array($res))
{
$category .= ” . $row['name'] . ”;
}
return $category;
}
/* jQuery Code*
$(document).ready(function(){ // this line just check the document is ready or not as you know it better
$(“select#type”).attr(“disabled”,”disabled”); // this is line disabled the type drop down when you open the page for the first before you select anything in the category list.
$(“select#category”).change(function(){ //this is the line which will execute when any change in value in the category drop down
$(“select#type”).attr(“disabled”,”disabled”); // this code will disabled type for time being when you select another category from the list
$(“select#type”).html(“wait…”); // this line will change the html for type drop down till your jquery return any results
var id = $(“select#category option:selected”).attr(‘value’);
// now this line will help in fetching the category id from the list . i think this is the one you looking for. Some time i just use normal jquery select option like, var id = $(‘#category’).val(). this also fetch the same value. the code in the web is very specific. so better try that one only.
$.post(“select_type.php”, {id:id}, function(data){
// this line is very important . this will do the ajax part to fetch the result as per the category id. select_type.php is the php file
// second parameter {id:id} is like {category_id:id} first id is variable like field name in the form, so when we fetch the value, we will use $_POST['id'] as in the first case (eg. $_POST['category_id']).
//function(data) – this data will hold the result from the select_type.php file.
$(“select#type”).removeAttr(“disabled”); // when the function return any result, first this code will remove the disabled attribute of type drop down.
$(“select#type”).html(data); // then finally populate the type drop down with the result (data)
});
});
I
For the issue with the second dropdown – check your jquery file.
when i put these dropdowns in a form and submit, second dropdown doesn’t included.
i am new to programming, so can’t trace out why it does so.
please help me.
You deserve a huge thank from me Maurizio Tarchini .
It helped me to get rid of a serious issue I’ve been revolving around.
Thank You!
Hello,
Can we include the id value in varchar and still the chained select list work? I know it doesn’t sound good. But i really want to use the value of select list as varchar as it is helping to perform other task. So need to stick with the varchar and cant use the int value.
I tried, but not working.
Robindra Singha – THANK YOU very much for your time to answer my question and explaining everything! It makes much more sense now… Really appreciate
Please send me the three chained select solution of yours. Also, you should post that answer. Nice article.