Check out my latest project: Full Frontal JavaScript Conference

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

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.

142 Responses to “Auto-populate multiple select boxes”

  1. 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

  2. Hi,

    Great work, Any way to make this code static javascript (non-AJAX)

  3. Michael Gamble May 15th, 2009 at 7:22 pm

    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

  4. Hey! Great plugin.

    One question: have anyone tried it together with MultiSelect plugin?

    Thanks!

  5. 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.

  6. how can we select multiple items at a time?

  7. 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.

  8. Only to say thank you Remy.

    Besides. I had the typical problem about JSON, but with your answer @HJ:

    [ { id: 1, text: "Cat" }, { id: 2, text: "Dog" }, { id: 3, text: "Worm"} ]

    && without forget:

                key: "id",
                value: "text",
    

    all goes OK. Excellent start for jQuery and JSON.

    $json[] = "{ id : {$row['id']}, text : \"{$row['text']}\" };
    echo '[' . implode(',', $json) . ']';

    -- && this editing system for comments is fantastic!!! --

  9. Thanks for this wonderful plugin ! it helps me save a lot of time!

  10. Awsome plugin!!
    You just saved my ass !!!
    God bless you...

  11. Hi, how do I apply 'selected="selected" attribute to one of my options?

  12. 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

  13. 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.

  14. Is there anyway to send dynamic data?

  15. In case of an error, is there anyway to clear all dependent select boxes?

  16. 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

  17. 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');

  18. 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:

    
    
          <script type="text/javascript">
          <!--
          // chained selects - see: http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/
          $(function () {
             var select1 = $('#frmAssignedUserID');
             var select2 = $('#frmAssignedAssetID');
    
             // note that we're assigning in reverse order
             // to allow the chaining change trigger to work
             select1.selectChain({
                target: select2,
                url: '/support/iss-100.php',
                type: 'post',
             }).trigger('change');
    
          });
          //-->
          </script>
    
          <!-- assigned user id -->
          <div style="display: block; height: 2.5em;">
             <label for="frmAssignedUserID" class="txtlabel">Reported By:</label>
             <span><select id="frmAssignedUserID" Name="frmAssignedUserID" size="1">
                <?php
                // get active users
                $query = 'select `userid`, `UserFullName` from `dbMain`.`view_users`';
    
                $result = mysql_query($query) or die (mysql_error());         // query executed
                $totalrows = mysql_num_rows($result);
                $i = 0;
                while ( $i < $totalrows ) {
                   $id = mysql_result($result,$i,"userid");
                   $name = mysql_result($result,$i,"UserFullName");
                   // output select option
                   echo '<option style="padding: .15em .5em;" value="'.$id.'">'.$name.'</option>';
                   // increment row counter
                   $i  ;
                }
                ?>
             </select></span>
          </div>
          <!-- /assigned user id -->
    
          <!-- assigned asset id -->
          <div style="display: block; height: 2.5em;">
             <label for="frmAssignedAssetID" class="txtlabel">Asset:</label>
             <span><select id="frmAssignedAssetID" name="frmAssignedAssetID" size="1">
                <option></option>
             </select></span>
          </div>
          <!-- assigned asset id -->
    

    This is the JSON data supplied by ISS-100.PHP:

    
    [{"id" : "20", "label" : "Verizon AirCard"},{"id" : "247", "label" : "USB Media card reader"},{"id" : "85", "label" : "Blackberry"},{"id" : "140", "label" : "AP01-063-505"},{"id" : "165", "label" : "AP01-023-A08"},{"id" : "211", "label" : "AP01-063-609"},{"id" : "910", "label" : "Brother Intellifax 750 fax machine"},{"id" : "306", "label" : "USB Bluetooth Adapter"},{"id" : "310", "label" : "Aten USB to DB9 Serial Adapter"},{"id" : "357", "label" : "Tripp Lite Power Inverter"},{"id" : "387", "label" : "Linksys WRT54G Wireless Router"},{"id" : "319", "label" : "AP01-063-408"},{"id" : "695", "label" : "Medeco Key"},{"id" : "166", "label" : "AP01-TEMP-109"},{"id" : "986", "label" : "Kingston USB flash drive - 4 GB"}]
    

    I don't know where to start and really appreciate any help I can get and the work put into this plugin!

    Thanks,
    Charles

  19. Note the extra comma on "type: 'post'," in the example above has been deleted and the error still occurs.

    Thanks,
    Charles

  20. 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

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight