Auto-populate multiple select boxes
To follow on from Auto-populating Select Boxes using jQuery & AJAX, I've had more than a few requests for how to do this for multiple select boxes.
In response, I've written a jQuery plugin and have included a simple example of three select boxes populating each other driven by a MySQL database.
Download
- Download the selectChain plugin
- View the demo PHP script source
- View the demo SQL source
- Demonstration
Prerequisites
- jQuery (this has been tested with 1.1.1 and 1.2 - so it should be fine).
- Basic knowledge of JSON
- Access to the server side for PHP and MySQL if you want the selects driven by a database.
Disclaimer
I have to admit I wrote the plugin pretty quickly, so it might not have all the bells and whistles you might want it to have - but it definitely does the job.
Also, the demo I've provided does not degrade if JavaScript is turned off. I advocate that you practise accessible JavaScript. This example is just to show the plugin working. Remember to make it work via the server-side too!
Demonstration
This demonstration uses three select boxes, the first (element category) drives the next (elements) which drives the next (attributes).
You should keep in mind this demo was written quickly, and I would never normally use the same name attribute on a select box, because when it comes to actually submitting the form, it would be a mess of values.
See the multiple-select population in action
Usages / Config
$('#categorySelect').selectChain({
target: $('#childCategorySelect'),
url: 'update-options.php'
});
Required
- target: jQuery object or HTML element
- url: string to Ajax request
Optional
- key: key of the key/value pair if you're returning an array of objects. Defaults to 'id'.
- value: value of the key/value pair if you're returning an array of objects. Defaults to 'label'.
- data: additional data values to send in the request (can be a string or object)
- type: Ajax request type, i.e. post or get
What next?
Here's a list of small bits that I think could be added to improve this plugin, but should be simple enough for anyone to write:
- Caching Ajax results.
- Ability to send the data (posted or get) based on a dynamic criteria - i.e. perhaps there's another static select box.
- Using meta data in the classes to link the targets to the parents - but this might make for sloppy markup.
Feel free to add any suggestions or improvements.
You should follow me on Twitter here I'll tweet about JavaScript, HTML 5 and other such gems (amongst usual tweet-splurges)


I believe you were looking at someone elses page, I'm not running PHP and those errors that you mentioned are php errors. My Ajax is returning fine, here's an example:
{"recordcount":4,"columnlist":"SPECIE,SPECIEID","data":{"SPECIE":["Baiji","Western Gorilla","Sumatran
Orangutan","Speke\'s Gazelle"],"SPECIEID":[1,2,3,4]}}
Two things that I need to know that I have not received an answer on:
1) An example showing how to use the "key" and "value" options, I could not find one on the documentation on this site or the jquery site.
2) The example shows how to return a JSON response with 1 value, how can i return multiple values? Example: specieid, specietype, specie, habitat, etc...
How do you work with multiple values with this plugin.
I hate hounding you about this but you're not giving me the answer i need. If you cannot give me that answer please tell me so that I can find another plugin or go elsewhere for help. I am wasting lots of time and quite possibly could be because I'm not asking the question right. I provided you with 2 links which are located in my previous post, one to an example that works that only returns the specie name and the other to an example that is returning specieid and speciename which I was not able to get working properly.
I look forward to your response either way whether you can help or not, I really have to move forward with this.
Thanks you!!!
@HJ - I honestly don't have time to back to all your emails (out of interest, have you stopped sending them, or was it via a cronjob - if so, you might want to stop the job as some point - ta).
The problem is that the returned JSON object should only be a straight array or array of objects with the key/value pair defined in the options - not the complex data structure you're sending back:
Or:
With JSON as:
Are you still receiving emails from me? Are they coming directly to you from my email address or what? I've only sent you 2 emails directly other than posting on the blog, I would never automate an email for stuff like this.
Please forward a couple of those emails to me so that I can verify whether or not they were sent by me. I can assure you that I would never spam you like that, I apologize for the inconvenience.
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
Hello! Great work!
How do i can select on view special option from request by ID ?
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select Replacement). 表单基本、输入框、选择框等(Form Basics, Input [...]
First off: many, many thanks for this plugin. I am working with Coldfusion 8 and it's implementation of doing AJAX select-box population is crap IMO, so I went back to my good ole' friend jQuery.
I am by no means a JS / jQuery expert, so I am not sure if this is a new thing, but I think I found a bug in your code. When trying to set my own options for "key" and "value" I found that the plugin was not using them and reverting to it's own defaults no matter what.
I reversed the order in your local settings variable per this website's suggestion (http://www.learningjquery.com/2007/10/a-plugin-development-pattern) and it seems to be working.
old code:
var settings = $.extend({}, options, defaults);new code:
var settings = $.extend({}, defaults, options);Disclaimer: I'm using jQuery 1.2.6
Thanks again for your work!
@Chief - good spot! I've swapped those around now so the defaults don't override.
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List Multiple Selects Select box manipulation Select Combo Plugin jQuery - LinkedSelect Auto-populate multiple select boxes Choose Plugin (Select [...]
[...] Auto-populate multiple select boxes. [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] View: Auto-populate multiple select boxes [...]
What could be the reason that my multiple select box works with Firefox but not IE7? Thanks for any suggestion!
Remy, are you plan to add cache ability of results ?
Remy, are you plan to add in script cache ability function for request results?
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
Hi Remy,
Very nice - this plugin will save me a lot of time. I have one question that I am not able to figure out:
In your example with the Category->Element->Attributes boxes - how would I have the "Element" select box send the selected Category along with the selected Element?
For example, if you pick a category of "Scripts" and then an Element of "Script" I would like the AJAX request to the server to contain the Element Category of "Scripts" and the Element of "Script", so that the server can lookup against the database where element_category='Scripts' and element='Script'.
Maybe your example isn't the best place for functionality like that. Maybe a better example data-wise would be the first SelectBox is City, the second is Street Name, and the final result SelectBox would be House Number. In order to get the list of House Numbers, you would have to know the Street Name and the City. It wouldn't work just to pass the street name to the server, because there are multiple cities that could have the same street name. So on selecting the street name, I would like the data passed to the server to contain the city name (previously selected) and the street name that was just selected.
Not sure if that makes sense?
I've tried setting an event when the first select box is selected to somehow re-create the "selectChain" for the second select box to include the data from the first box in the call of the second box, but it doesn't seem like a good method.
Not sure if this is possible, but if you have an easy solution I would sure appreciate a nudge in the right direction.
Thanks in advance!
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
Remy,
Thanks for the code. I also have a similar need to Brian with sending multiple variables for the database to check against.
I have an additional request too...In my page, some of my select boxes do 2 things - 1. populate the elements in another select box, 2. update another div tag with a picture of the chosen item.
E.g. Select box "vehicle" lists a bunch of different vehicles and on selecting, a picture of the chosen vehicle appears somewhere on the page, and then select box "model" lists the models based on the vehicle chosen in the 1st select box.
I do have another ajax script that works, but I much prefer the way your script updates the select boxes over my existing script.
Any pointers would be greatly appreciated!
[...] Auto-populate multiple select boxesA plugin to autopopulate select boxes. [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] http://remysharp.com/2007/01/25/jque…ext-box-hints/ http://remysharp.com/2007/09/18/auto…-select-boxes/ http://jquery.com/blog/2006/11/14/ex…nu-screencast/ [...]
This isn't working for me when I test in IE6 (using the most recent JQuery: jquery-1.2.6.min.js ). Am I missing something?
It's not populating the boxes and it's throwing an error (even on your demonstration page):
Line 28 / Char: 5259 / Error: Automation server can't create object
Is this not supported on IE6? This is a great post and I had already started implementing a version of this before testing in IE6, if there is a workaround or if i'm missing something please let me know, thanks!
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
would you help me with my database structure , i couldn't implement the script using my current setup.
I'm new to jQuery and I just can't hardly modify the code to fit my setup.
$(function () {
var province= $('#fprovince_id');
var amphur= $('#famphur_id');
var tumbol= $('#ftumbol_id');
amphur.selectChain({
target: tumbol
,url: "../plus/district_json.cfm"
,type: 'post'
,data:{fdistrict:'tumbon'}
});
province.selectChain({
target: amphur
,url: "../plus/district_json.cfm"
,type: "post"
,data: {fdistrict:'ampher'}
}).trigger('change');
});
in step 2 (when change famphur_id) ie6 and ie7 it don't send fprovince_id value (work on firefox 3.1) you can see mistake line? i use jquery 1.2.6
Can anybody give me an example of how to add the id as the value of the select box? like:
option value="1"
I've been trying, but no luck. Thanks for any help.
@Justin
Here's what I did.
If I have select Box A that populates Box B:
src_sys.change(function() {
A.selectChain({
target: B,
url: '/cgi-bin/script.pl',
type: 'get',
key: 'id',
value: 'name'
});
I have my "script.pl" script return JSON like this:
[{id: 1, name: "ONE"},{id: 2, name: "TWO"},{id: 3, file_name: "THREE"}]
The select (B) turns out like this:
Hmm - it took out my "select" and "option" tags...
Basically, the id of the first option is 1, and the text is ONE, and so on....
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
Hi,
thanks for excellent work! It works like a charm!
One minor bugfix, it should be:
setTimeout(function () {
settings.target.find('option:first')
.attr('selected', 'selected')
.parent('select');
settings.target.trigger('change');
}, 0)
because if you chain the trigger method, and you have no options in any of the select boxes from ajax, then the trigger will not occur and we want it to clear all the rest of boxes, don't we?
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Rellenar automáticamente Selects Múltiples [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Auto-populate multiple select boxes [...]
Hi Remy,
Is there any way to add a callback function? If not, consider this a feature request
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
hi, is there a way to show an icon while script is loading data?
[...] Auto-populate multiple select boxes [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]