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.
Thanks for this plugin ! it saves me a lot of time !
How can I assing the default 'elementSelect' ?
Best regards and thank you for this great plugin.
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
hi, nice tool!
it must be a very stupid question but I'm trying to apply this tool to postgreSQL, but I always get an empty [] value. It means that the array $json[] is not filled in the while statement. But the dbase connection and the query is correct ( I can check applying a echo "data: ".$row[0].""; and all the data is displayed).
Thanks!
[...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]
@pere - first things first, I would ensure the query is returning results. I normally do this by:
That way I know for sure the values being passed in to the query (and I'll run that directly in to the database).
The rest of the code looks fine, so I would start there.
The js dont work with ie due to a bug of ie
http://support.microsoft.com/kb/276228/fr
(select chain bieng the new one )
Solution
well hum .... this should be more readable :
http://corpo.julbox.net/jquery_select.js
[...] Auto-populate multiple select boxesLanuch Demo/site [...]
@Jul - thanks for the heads up on the IE bug. I've patched the plugin to use your suggested code (note that your version hard codes 'entity' as an id, break the chainability of different selects - it's fine in the plugin code though).
Cheers.
Remy,
I solved the question like this; thanks.
Hey, it still automaticly chooses first node in box and gets its children. And it would be nice to be able to select node by id
[...] 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 - LinkedSelectAuto-populate multiple select boxes.Choose Plugin (Select Replacement). 表单基本、输入框、选择框等(Form Basics, Input [...]
This is great, I'll implement it now and give the URL, so people have another example
hi,
it's very nice, but I need following:
select box 1
select box 2
select box 3
result
it should be like a filter for result...
please help me, I have no idea
[...] 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 and thank you about this excellent work.
How can I select pre-select an option that is contained in a db row?
I have this:
$json[] = '{"id" : "' . $row->id . '", "label" : "' . $row->name . '"}';
something like {selected: "selected="selected""}
Regards guys
HI
I'm trying to get this to work to select Make/Model/Year for cart parts .. problem is Year is stored in another table. So I tried to make the table names variables to they will pass in ... it obviously works the first time through cause I'm getting the correct list in the second box - but it doesn't seem to pick up the third column.
So I must be missing some logic about how this all works.
http://www.dbkonline.com/MYWEBSITE/QP/make_model5.php
Code below.
thanks - I hope someone can help.
Donna
DBK Web Development, LLC
I have this:
Ok - I gave up on the two tables and got it all working here
http://www.dbkonline.com/MYWEBSITE/QP/make_model6.php
However - now when I process the form - since all the options are called "category" - I loose everything but the last one ...
How can I pick up all three answers ... I tried saving them ... changing the name and pssing that in as a variable but nothing seems to work.
Can you show and example of processing this form based on the selection?
thanks
[...] 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 [...]
How can I modify this to work with coldfusion5 and MsSQL?
[...] Select List Multiple Selects Select box manipulation Select Combo Plugin jQuery - LinkedSelect Auto-populate multiple select boxes Choose Plugin (Select [...]
Hi there,
Thanks very much for the plugin. However, I can't seem to get it to work with the structure I want.
I want to return a JSON object of the form:
[{"id":112,"name":"Value 1"},{"id":213,"name":"Value 2"},{"id":233,"name":"Value 307"},{"id":401,"name":"Value 4"},{"id":415,"name":"Value 5"}]
So I am using the plugin as follows:
$('#categorySelect').selectChain({
target: $('#elementSelect'),
url: 'select-chain.php',
key: "id",
value: "name",
}).trigger('change');
I see that you have a very similar structure commented out in the sample code. However, when I do return an object of this form, I get "Undefined" for each option in my select box. Therefore, how can I make this work, or can you suggest the best structure to return a list of id's with the values?
Thanks v much!
[...] Auto-populate multiple select boxes [...]
[...] Auto-populate multiple select boxes [...]
[...] Select List.Multiple Selects.Select box manipulation.Select Combo Plugin.jQuery - LinkedSelectAuto-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 [...]
Hello, i have a question about the 3 select.
They have the same name "type".
According to you, how is it possible to know the value of the first select or the second,...
In a POST ==> $example = $_POST['type']
Thanks a lot
I wanted to post that I have the script working with multiple tables now. The problem was the JSON returned was returning an entire queryset encoded, but what I should have done was return only the column that I needed. AJAX is new to me, but JQ is helping me along with it and it's starting to make more sense the more I play with it.
Thanks for the script!
{"recordcount":4,"columnlist":"SPECIE,SPECIEID","data":{"SPECIE":["Baiji","Western Gorilla","Sumatran Orangutan","Speke\'s Gazelle"],"SPECIEID":[1,2,3,4]}}
I'm trying to use the key/value options, how do i do that with above JSON? The component that i'm using returns the above code, i'm not sure how to grab the key and value out of it for your plugin. The other thing that i'm trying to understand, how do I do the following:
SPECIE
Are there any examples that show how to use the key / value options?
Look forward to your response or anyone else that can shed light on the matter.
Thanks!
that's it, i give up, i'm not going to try to put the option tag in, i'm giong to explain it and I hope that it will make sense. i'm trying to add the value attribute to the option tags that are within the select. I want to take the id and the name and populate like that. does this plugin work like that or do i have to make my own homegrown solution?
@HJ - do you have a link to an example what you're talking about?
[...] Auto-populate multiple select boxes [...]
Hi Remy, thank you for replying, sorry about all the unsuccessful posts, i kept receiving errors on the blog.
Anyhow, here is the link to the sample page that I put together, it's not exactly like yours , but it will give you an idea:
http://ts.7079.net/jquery/cascadingSelects/
I had the script working when I was just returning a single column of data and not the entire query. I was hoping that I can return the entire query and the data rather than having to strip it down for the plugin so that I can use the same data elsewhere if need be. I was hoping to find out how I can take the specieid and drop that in the value attribute of the option tag and than between the option tag drop in the specie name. I've tried every which way possible and have been unsuccessful with it, hoping that you can shed some light. Also, can you explain how to properly use the key and value options of the plugin? I had a tough time and tried so many things but could not get it to work.
The working example with the JSON only returning a single column from the database rather than the entire query is here:
http://ts.7079.net/jquery/cascadingSelects/index_old.cfm
I look forward to your help and I would like to thank you in advance. Once you shed light on this, i'd like to give you the working ColdFusion script to offer on your site for those out there who are in need of your plugin and work with CF.
Thanks again!
Is there a way to add a static object to the selection list?
like "No Screen" for a computer build.
Hello Remy, did you read my question ?
Thanks a lot if you have a solution.
Have a nice day.
Usai.d
I apologize being an absolute beginner. I tried to implement your idea but I aleays get the error message: "an error occurred". I have set up the database. What could be wrong? Thank you!
@Haja - if you provide a link to an example then someone might be able to help.
Otherwise, you can do one of two things:
console.log(arguments);How to preselect values ?
@HJ - I keep receiving emails from you asking the same question over and over. I'm going to post here, what I replied with in the first email:
> Have a look at the output of your Ajax URL in Firefox. It's likely this is breaking the success function and bombing out.
I've had a look at the Ajax response (via the Firebug option - show XMLHTTPRequests) and can see the output of your JSON call is this - which obviously breaks the JSON parser:
Hi Remy -
Great Code! I mostly reformatted it to work for my needs. However, I need a little guidance if you have a second... I have a database populate the first box, when the item is selected it populates the second box which returns either P,C or I (a row from the database). What I would then like to happen is have the third box return a series of options (not from the database, I would probably use some sort of IF statement) based on what gets populated in the second box. I have tried and tried to get this to work but I can't figure it out. I am new to PHP, MySQL, AJAX, and JSON, but I was able to get this far....soooo... How do I got about making the third select box selected from information in the second box from a source other than the database? Let me know if this post is too confusing.
Thanks!
Ok well to pre-select an option here is some pseudo-code I tested
inside the for loop add
o.selected = true
@Peter was that for me?
Hi All!
Sorry for my not goog english, but I need the same example as HJ's http://ts.7079.net/jquery/cascadingSelects/index_old.cfm,
but it must work at two another tables! For example first table is COUNTRY and second table is CITIES! How can I change this code?
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.