The first part (before the first function) sets up the XMLHttpRequest() object. The initCs() function loads the second select box onload and sets an onchange event for the first box. Onchange, the fillSelect() function is called. The selected option is sent as a variable to a PHP page, 'csa_ajax.php', which looks like this:

That takes the value of the selected option and chooses the appropriate array for it. This would often be done by calling data from a database, but for convenience, I've used a switch(). The last bit echoes each of the items in the array preceded by '|' for the javascript to split up into individual items. The go() function takes the output from the PHP page, breaks it down, makes new text nodes out of each item, appends them to new option nodes and adds the option nodes to the select box.

Comments

#1

2007-10-24JSmoke says :

This works slick. Here's a little variation that would make an <option> become <option selected> based on the first value.

So you could look up the first value entered in your database and then make that selected in your second select menu. You'd have to return the value of the <option id> from your database.

Just wondering if there is a way to store the arrays into a database...and then say make a form to where you could add to the arrays.

Like say you wanted to add a city to the United States...

#8

2008-01-09Nick says :

i too, would also like to know if its possible to have the cases and arrays outputted by a database?

#9

2008-01-11BonRouge says :

/\/\ongoose / Nick,
Yeah, it's easy enough to use a database to do this. I would have done that here, but I just couldn't be bothered.
The query to the database would look something like this:<?php

$country=@$_GET['country'];
$q = mysql_query("SELECT city FROM cities WHERE country='$country' ORDER BY city ASC");
while ($r = mysql_fetch_assoc($q)){
echo "|".$r['city'];
}

?>
This is assuming you have a database of cities with maybe three fields - id, city, country.

I hope that helps.

#10

2008-05-02Simon says :

I want a script with two chained selects, the first one is for a main category, all the categories are extracted from a database.
The second select contains subcategories which are also selected from a database. Is this remotely possible?

I have this script up and running, but I need 2 or more dependent selects, (not just 1). I'm running into a lot of trouble tyring to reuse the XHR object in IE for the 2nd and 3rd, etc. dependent select fields. I've checked the solutions on http://keelypavan.blogspot.com/2006/03/reusing-xmlhttprequest-object-in-ie.html and other pages with no luck. Any thoughts on what the problem might be ?

#13

2008-06-30Sam says :

Hi,
I am not sure why not, but it works very well with Firefox, not with IE. Any idea, what I may be missing?
Sam

#14

2008-06-30Sam says :

I opened the link with IE from item # 11 above, posted by BonRouge that also did not work. Thanks.

#15

2008-07-01BonRouge says :

Sam,
Sorry about the very late response (maybe you'll never see this... ).
I see what you mean about the link in #11 - that doesn't work in IE. (I'll try to get back to it soon and sort it out). This page works fine for me in IE though, so I'm not sure what your problem would be there.

#16

2008-07-02Sam says :

Hi Bon,
Does the script from Item # 11 works on your PC, when you click that one. On mine, it not only did not work, but also showed duplication of the contents of the second selection everytime I made a selection from that option list. Please advice!
-Sam

#17

2008-07-07Greg Tallent says :

Thanks, Bon. Script works fine, including the code that retrieves cites and countries from a db.

#18

2008-07-12Marvin says :

i need the second chained box to have a value like this:
<option value="1">Town Branch</option>. how do i print this? the data is gotten from a database, a user selects a bank and then the bank's branches are called from the database

I have added two new lines:
var values=cities[ i ].split(';');
x.setAttribute('value', values[0]);

Both inside the for-loop. Now the only thing you hafte to do is change the .php file to echo in this format:

|id;text|id;text

Ex:
|1;London|2;Manchester

It works fine :-)

#20

2008-08-22Anders (again) says :

Sorry, I also alter the line:

var y=document.createTextNode(values[1]);

#21

2008-09-14Goody says :

Hi BonRouge,

Thank you for this wonderful code.

I tried your three field chained select menu given at #11 and I am not having any luck making it work on IE6. However it's OK with FireFox.

Your help will be much appreciated.

Regards
Goody

#22

2008-10-04kristin says :

ah, same here! Please help.

fujiwarachiaki .... at gmail.

#23

2008-10-07Marty says :

Would it be possible to post all the code files in a zip, on here? Also, how would it work if the data for each select needs to come from a db table?

#24

2008-11-05DM says :

Hello,

Somehow I manage to workout this code and it acctualy helps me
Some time it took time for that second 'citiy' combo box to load.

I wonder is it possible to implement some (ajax) animation .gif that will disappear when 'city' list is loaded ?

hope you get me

Best regards,
DM

#25

2008-11-19sercan says :

hi there,

i am a newbie on AJAX.. i just copy&pasted the codes you wrote down here.. now, i just don't know where to put the window.onLoad=initCs() code.. i guess because of this issue i couldn't make the script run

nothing happens when i click on the countries from the dropdown menu..

#26

2008-12-29PP says :

Do you modify more I need 2 selectionb things life contry selected come to state and state selected to comes the area. etc..

#27

2009-01-13Josh says :

Hi Guys, I'm pretty new to all of this and just need some guidance here. I am in need of two select boxes such as this template is designed for. The first box is for the 'Make' of a vehicle, and the second, 'Model' of vehicle that auto-populates depending on first select box selection. Anyhow, if someone would be kind enough to explain to me where the groups of code shown in the tutorial are to be placed. I copy and pasted the html code into the a text widget to place the select box in the area of the website I want. I am just unsure where the javascript code is placed along with this tidbit of JS - window.onload=initCs; . If I understand this somewhat, as I believe I do, the PHP script is placed in a php file titled: csa_ajax.php .

My last question is, once I get everything in place, can I just edit the id names and change them to suit my needs?

Thanks in advance,
Josh

#28

2009-01-30Sathesh says :

Thanks Anders and all of you..

I was exactly looking to split this sort of thing in JS with the response text in the form: ?VALUE1;DESCRIPTION i.e. <option value="VALUE1">DESCRIPTION</option> .

I used '?' since I used '|' for some other purpose.
I got a very similar function like #19 Ander's with my own parameters and stuffs.

hi i want two chained select box 1 with options to select telephone set and in second select box quantity and when we select quantity ten there,price should be appeared next to quantity select box...........can any1 help ??????????????

#31

2009-07-24Andy says :

Bon,
Great script and have it working fine as able to fill both select boxes from my database. One query: If a particular value in the second select box has already been selected by a user (and stored on my DB) is it possible to have the javascript add SELECTED to that particular option next time they visit the page?
Thanks

#32

2009-07-25Andy says :

Also I forgot to add- is it possible to have the menu more than 2 levels deep?
Andy

#33

2009-08-23faiz says :

Hai Bon,
thank for the code but i have a little big problem with it.
how i want to use two chain select in same page?i having a hard time solving it tq.

#34

2009-10-08pete says :

Not sure why but I get </BODY></HTML> on the last option.

#35

2009-11-17windjared says :

ok, for those of you who wants to have more than 2 selected boxes, for example, i'm having 3 selected boxes, the second is depended on the first one, and the third one is depended on the second one, you need to have multiple functions:
function fillSelect(itm)
{
var url = "http://develop/web/Inventory_AJAX/inventory_ajax.php?item=" + escape(itm);
//using ajax here
request.open("GET", url, true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
if (request.status == 200)
{
var response = request.responseText;
var list=document.getElementById("idmake");
var makes=response.split('|');
for (i=0; i<makes.length; i++)
{
var x=document.createElement('option');
var y=document.createTextNode(makes[i ]);
x.appendChild(y);
//Damn Microsoft
//**important, the following line cost
//me freaking 3 days of researching, you have to set //the value of each 'option', otherwise, the stupid //IE won't read it
x.setAttribute("value",makes[i ]);
list.appendChild(x);
}
}
}
}
request.send(null);
}

what if you have multiples of this chained select.
the id will be the same,but then you will have change in country[0] corresponding to city[0], change in country[1] corresponding to city[1] and so on...
How to implement this script in array form?

#44

2010-11-12BonRouge says :

jy,
Here's a page with many of these: chain select js boxes. The difference is that this example uses arrays rather than AJAX and a database. I hope you can use that or see how to adapt it.

#45

2010-11-12jy says :

Can you post the code, i am not sure how to modify the response page,

#46

2010-11-29jy says :

I was able to solve this by first creating a loop in php by creating multiple drop down list , and giving them different ids, then use javascript to get the id from the dropdown list.

#47

2011-03-22not spamming-kevin says :

dunno if people still checking this but I have gotten this script to work perfectly... The only thing I am having trouble with is trying to load the page with the 3 drop downs filled in with what has been stored per user.

I can get the first to populate with the 'selected' element but the send list loads all list items and no selected.

I have the 2nd and 3rd values in both my index page and my chain.php page but I can't figure out where to put them...

#48

2011-04-19jj says :

hi any body write how to save this form. That means if i add submit button does it work. how this submit button save data to mysql database table

#49

2011-04-20Paul says :

Hi,

Is anyone up for making the following three wheel spinner chained dependency from data in a MYSQL DB?

Great script, however i am having trouble connecting it to a database. The connection works fine, but i want to retrieve both an ID from the database that i want to use as VALUE in the option list and offcourse a displayed text from the database, for instance a city. I mean: <option value="1">Amsterdam</option>, both coming from a database