I’ve finally gotten around to writing & releasing a jQuery plugin that allows you to create any number of related/dependent select boxes in a form. I’ve yet to find a decent solution and needed something that was fairly customizable and could retrieve data using AJAX/JSON, so here she is.
From the GitHub docs:
jQuery Related Selects is a plugin that allows you to create any number of select boxes whose options are determined upon the selected value of another. You pass an array or object of select box names, and the select boxes will depend on each other in the order in which they are passed in.
When a select box is changed an AJAX request is sent to the file specified in the onChangeLoad property, passing the selected value of each select box as parameters. For now the data must be returned in JSON format. An <option> must have a legitimate value in order to trigger the script. An <option> where the value is blank (value="") is used for the defaultOptionText option (see below).
This script provides a high level of customization. You can set the options once for each select to use, or set the options on a select-by-select basis. You can also start your markup with pre-populated options and selected values.
Usage
A basic example. Changing the "stateID" select updates the "countyID" select and so on. The values of all four select boxes are serialized and passed to datasupplier.php, which returns data for the next select box in JSON format.
<form> <select name="stateID"> <option value="">Choose State</option> <option value="MA">Massachusetts</option> <option value="VT">Vermont</option> </select> <select name="countyID"><option value="">Choose County</option></select> <select name="townID"><option value="">Choose Town</option></select> <select name="villageID"><option value="">Choose Village</option></select> </form>
$("form").relatedSelects({ onChangeLoad: 'datasupplier.php', selects: ['stateID', 'countyID', 'townID', 'villageID'] });
Options
selects
Required. An array or object of select boxes you want to be dependent. Each one will depend on each other in the order in which they are passed in. If you want to override any of the options below on a select-by-select basis you can pass this as an object. See examples.
onChangeLoad
Required. The file to call to retrieve data when a select box is changed. Data must be returned in JSON format for now.
loadingMessage
Optional. The text to change the sibling select box to during the AJAX request.
defaultOptionText
Optional. The text inside the default <option> tag after AJAX populates a select box. This is typically the text where you instruct the user to choose an option. If this option is not provided and an <option> tag with a blank value attribute exists in your markup, that text will be used.
onLoadingStart
Optional. A callback to fire when the AJAX call starts.
onLoadingEnd
Optional. A callback to fire when the AJAX call ends.
onChange
Optional. A callback to fire when a select box is changed.
11-18-2009: Bug fix & new features update
I’ve fix a bug where refreshing the page makes all selects become active, and added a new option and callback:
disableIfEmpty
Set this option to true to keep the next select disabled if the previous does not return any results.
onEmptyResult
Optional. A callback to fire when no results are returned after changing a select.
12-2-2009: Update: Return data in HTML format
Data can now be returned in HTML format by using the new dataType option. Set it to either ‘html’ or ‘json’ (default).
Related posts:









I seems that there are some php requirements for this plugin to work.
Wamp server on Win 7 will not load related select (PHP 5.3.0), just stay on loading, where MAMP server on Mac OSX 10.6.2 loads fine the same file (PHP 5.2.11).
Now I checked PHP core on both servers and made sure they are identical. No joy.
JSON is enabled.
Are there some other settings to consider Thanks.
@miskotes, it probably isn’t able to parse the JSON returned from the server. Look @ the datasupplier.php file on the GitHub page for an example… how are you creating the JSON? Also try using Firebug to see what the response looks like.
This is a really useful plugin, great work !
One thing it would be nice to be able to do is to cache locally already fetched data.
It doesn’t seem to be the case at the moment or am I wrong ?
@Francois, not yet, but it is on my todo list.
thanks man for the great work,man i was looking for something like this for a while maybe you could post a database example where you pull options from records
[...] Get in Touch Welcome to my online development portfolio. I am a website developer living in Newton, Massachusetts and am passionate about developing functional, standard-compliant, user-friendly websites. « jQuery Related (Dependent) Selects Plugin [...]
Hi Eric,
great work and thanks for sharing.
I would like to work with selects having a size of 10.
My problem is that if I went into level 4 and go back to level 1, level 3 and level 4 are disabled (which is correct), but I can still see the last options in these levels.
Is there any way to remove the options from these levels?
I hope my problem is understandable and sorry or my awful english.
Hi Eric,
Your plugin is superb. Any suggestions how to populate selects using database?
Thanks
@Jens, the default option (where the value=”", and the text typically instructs the user to select an option) in each disabled select should automatically be selected. Do you want to completely empty the select boxes?
@Alex, set the onChangeLoad argument to a file or URL which executes a database query using your favorite server-side language. The query should retrieve some kind of ID for each option’s value attribute and text to add in between the tags. Encode the results into JSON format; your programming language probably has a method for this, like ColdFusion has jsonencode(). Print the JSON string to the browser, and you should be all set.
Hi.
This is a very nice tutorial.Can someone post a remake datasupplier page from .php to datasupplier.cfm (using coldfusion)?
Hi,
This is a nice plugin that works on FF, Safari and Chrome. But i have no luck on IE 8!
Can you help me ?
Alex
After MANY MANY experiments, some installing of debuggers in IE (namely Debugbar and firebug) i have now concluded that IE is a piece of crap…an abomination of this world!!
The solution to my problem was simple, and yet so showstopping.
I kept sending
{“CHA”:”Chatham”,”DEN”:”Dennis”,”YAR”:”Yarmouth”,}
in the AJAX response…Notice that last , ? The last , should not be there, IE does not understand that.
EVERYONE else does tho…
Alex, yeah, I usually look for extra commas around object literals first when only IE is throwing errors… but, it sounds like IE is doing something right here because that JSON is invalid
Also, if you’re running version 1.4, jQuery will not fire the AJAX “success” callback if it receives malformed JSON back from the server. Just something to be aware of. JSON Lint is a good JSON debugging tool for these situations.
Thanks for your reply.
The least I would like IE to do is at least throw an error if the JSON structure is broken. But it does not, even with “Show Warnings on page” option turned on. Which makes developing for it a living hell.
On a related note:
{
“CHA”: ”Chatham”,
”DEN”: ”Dennis”,
”YAR”: ”Yarmouth”
}
Will receive an error in JSON Lint. Go figure..
Is there any other debugging tools available? I receive the same error on another call now when i try to pull _html_ via Jquery. Same as before, all other browsers work, IE doesnt..
And this time I am pretty sure its the correct html!
Thanks!
Scratch my last comment. Ran my code through w3.com validator and i was missing a div…
Thanks yet again for a very good plugin.
First I want to thank you for your great plugin.
I need help :
I have 3 related listboxes (category->subcategory->subsubcategory) and I want triger 4′th listbox “type” from second listbox “subcategory”.
How can I do this.
Thanks
Hi Morowind, there’s no way to do that at the moment… each select depends on the previous one in the order in which they were passed to the “selects” parameter.
Thank you very much .I will try some other ajax call onchange event.
Great work anyway.
I’m back again .
How can I hide selectbox if ajax response or selectbox is empty or null (change disable attr) ?.
This script doesn’t work for multiple instances in same form , or I am wrong?
Thanks
Hi Eric!
I’m trying to get this working with two boxes.
Nothing happends with the second box, accept for the “Please wait..”
From what I can tell the data-file isnt loaded:
onChangeLoad: ‘quick_search_data.php’
If I write a simple echo “Hello!” it should be seen on the screen if the data-file is loaded, right?
Regards, Per
Greetings from Sweden
Hello guys,
Like wrote, this select doesn’t work on PHP 5.3 version, then i select first selection firebug gives me an answer
”
Notice: Undefined index: countyID in C:\wamp\www\testinis\ehynds-jquery-related-selects\datasupplier.php on line 7
Notice: Undefined index: townID in C:\wamp\www\testinis\ehynds-jquery-related-selects\datasupplier.php on line 8
Notice: Undefined index: html in C:\wamp\www\testinis\ehynds-jquery-related-selects\datasupplier.php on line 9
{“BARN”:”Barnstable”,”PLYM”:”Plymouth”}
”
that means that JSON works OK, it has the values {“BARN”:”Barnstable”,”PLYM”:”Plymouth”}, but they are not shown.
Sorry for my english
Per, probably not. If you’re using JSON as the datatype, jQuery will not sure the “success” callback if the response is not valid JSON, so you won’t see anything. If you’re using HTML as the datatype, you need to return option tags back to the client.
Bufer, that’s a PHP error. My guess is you’re tying to refer to variables that do not exist.
Strange, i’ve just extracted your code, thats all, any changes, and im running wamp with php 5.3 ver. and the code doesn’t work, any hints? You are smart guy and i know there is something on your mind
Very useful plugin. Two feature requests if you still have time to work on this plugin:
1) allow user to select the GET or POST method. This is pretty trivial. Ive hardcoded POST in your plugin now. This is necessary for things like codeignitor that are POST centric.
2) allow user to add additional parameters in the ajax call. Im using your code in a place where the value of the options im returning are dependent on another parameter. I can work around it, but I think it would be useful.
Thanks for the feedback Cor. When I get a minute I'll add an “ajax options” parameter so you can pass in any of the $.ajax settings.
Hello,
Great plugin!
Is there a way to set the url of onChangeLoad during a onChange callback.
I would like to format der url according the selection.
Thanks,
Aldo
Would be perfect if there's a connection with mysql, but still good job (Y)
Your data source can be anything you'd like. Instead of serializing an array (like in the demos), serialize a database recordset instead.
There is not, but I agree there should be better support for this. Stay tuned..
Hello ,
thank for the great plugin. But I have problems to adapt your code to an example using mysql.
Is it possible that you can post a dump of the database and the code for the selection of your example???
Hello ,
thank for the great plugin. But I have problems to adapt your code to an example using mysql.
Is it possible that you can post a dump of the database and the code for the selection of your example???
Very nice plugin, but… alas, my CMS generates the selects with square parenthesis in the name (i.e. name_[uid26] )!
Is it possible to make it work?
Thank you!!
hi Eric,
I have a problem – I created exactly the same files like in your sample. but when I change the selected value – the child select list says “please wait..” all the time.
How can I make that work? I am using windows 7 and Firefox& IE8.
I really liked your plugin – and I would like to use it in the future.
Thanks ))))
This code is great thanks… I just have one problem. When i use in a form and then press the submit button, the secondary field refreshes and the form validation detects it as an empty field and won't submit.
Is there anyway i can stop the select box refreshing?
thanks
Great plagin!
Could you please help me with a such configuration:
5 select list, when I choose from the first one, the rest loads option values. All 4 are dependent from the first one.
How can it be done?
Great. But it would be nice if it was possible to create the relatedSelect boxes on demand. So that there were no empty boxes.
Nice plugin! But i have a problem, i need to load the page, whit the state, city, town, village, all whit the “Selected value” (it is a Update Module), how can i set a “SelectedIndex” to the selects automatically, by default.
Tnks a lot! is too easy to use! Really nice,
help plz
Very nice plugin. My question is regarding the HTML dataType. Your example only chains two selects, How can I chain multiple selects and get my select data from an HTML data source?