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)
Hi,
First of all, thanks for taking the time to write this
Now, I've almost got this working how I want.
I've got 4 boxes (continent,country,city and state).
I'm doing the selection process a bit different, with:
$results = mysql_query('select * from glinks_Category where Full_Name LIKE "' . $_REQUEST['category'] . '/%" and CatDepth=' . $_REQUEST['CatDepth']);
Now, this works fine at the moment - but the problem is, I need the value="FULL_NAME", and what the user sees in that box to just show the last part of NAME.
For example, we have:
Europe
Europe/United Kingdom
Europe/United Kingdom/Surrey
Europe/United Kingdom/Surrey/Guildford
..and those would in theory, generate to:
Europe
United Kingdom
Surrey
Guildford
Is there any way of doing this?
Thanks again!
Andy
Hi,
Great work, Any way to make this code static javascript (non-AJAX)
I need help with setting this up on a website, with a Year > Make > Model > Trim selections. Can someone help me please, I am knew at the whole database and scripting thing. I am a simply HTML, FLASH, Graphics guy, don't do much jQuery or Ajax or JSON. I am willing to pay someone $50.00 paypal to help me. I need it asap though. Thanks! email me at: mike at mikonmedia.com
Hey! Great plugin.
One question: have anyone tried it together with MultiSelect plugin?
Thanks!
Thank you, thank you, thank you.
I'm one of those people who's just starting out with AJAX and jquery and of course, I'm biting off more than I can chew.
Thanks to you, I finely have "what I had in my head for my next project" working in a real life example.
how can we select multiple items at a time?
ok answering my own question. I noticed some other asked as well.
In order to select multiple items change the request method to post, change the select element name from category to category[]. This is create a sub array in $_POST of all your selected items.
Only to say thank you Remy.
Besides. I had the typical problem about JSON, but with your answer @HJ:
&& without forget:
all goes OK. Excellent start for jQuery and JSON.
-- && this editing system for comments is fantastic!!! --
Thanks for this wonderful plugin ! it helps me save a lot of time!
Awsome plugin!!
You just saved my ass !!!
God bless you...
Hi, how do I apply 'selected="selected" attribute to one of my options?
ok i posted this under the old topic by mistake, reposting here. Hopefully someone will respond.
Ok i've extented this to a wonderful solution that uses 5 select boxes that allow you to select mutiple items at a time. for each list and also integrated a search box for the final list.
but of course my end user wants more! .... so for my lists are a simple chain. so one selection affect the list immediatly next to it and so on.
well i want to have it where say my first selection affects the 2nd and also the third and maybe 4th. However u cant figure out how to pass selected items from the first list to another.
here is a snipplet of what i have
customer.selectChain({
target: market,
url: callback_url,
type: "POST",
data: { ajax: true, multsel: market_selects, cust_val: customer.val().join(",") }
}).trigger('change');
So this customer selector triggers a changes in a market selector box. This all works fine. But look at the data line...i assume ajax:true tells it to pass the selected values from the current list.
multisel : market_selects is a list im getting from PHP to save state when the page is refreshed... this works well.
this very last one cust_val: customer.val().join(",") is where i was hoping that the selected values from the customer list would be passed to the server via ajax. ....
However it passes the enrtire list not just selected values. I know this is sorta right because an alert function shows only the selected values
Any help fwill be greatly appreciated
Remy, I'm not sure if someone commented this before, but I guess a good "what's next" is "caching selections", like whenever a user makes selections in a child, then changes the parent, and changes back again, the child will still remember the selection.
Is there anyway to send dynamic data?
In case of an error, is there anyway to clear all dependent select boxes?
Thank you for this great code. It works perfect!
Please allow me one question. I would like to make the trigger only on select. How could I do this? The way it is right now, it pulls the data for argument AND element at once. I would like to only pull data if the user selects a field.
Kind regards, Merlin
Hi, Thanks for the gr8 plug-in..
I have a situation where I need to chain two select boxes - both of them are created at runtime.. how can I use selectChain on runtime elements ?
In the same function where I create two select boxes - I do the following but doesnt work - Any suggestions !!
$('#newID > #Select1').selectChain({
target: $('#newID > #Select2'),
....
}).trigger.('change');
Can someone please help me??? I have two selects on my form. I want to update the second select using an ID from the first select. When I make a selection from the first select I get the javascript pop-up "an error occurred".
The following is the relevant code from my PHP page:
This is the JSON data supplied by ISS-100.PHP:
I don't know where to start and really appreciate any help I can get and the work put into this plugin!
Thanks,
Charles
Note the extra comma on "type: 'post'," in the example above has been deleted and the error still occurs.
Thanks,
Charles
Hi Remy, thanks for the scipt is works great. Maybe a simple one for you here.
My site http://www.onlyprojectorlamps.com/website/, all i want to do is echo the Price as a string. The Price is the 3rd chained box which will only echo 1 result, so i dont need it as a SELECT. Can this be echoed into a DIV?
Your help most appreciated!
Thanks