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. [...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select Replacement). 四、表单基本、输入框、选择框等(Form Basics, [...]

  2. [...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]

  3. [...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]

  4. [...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]

  5. Thanks for the code.

    Is there any way to bind two menus to the same menu. (ie. When I select a value in one menu I need two other (sibling) menus to be updated and then these two in turn cascade their changes down to other menus)?

    Matt

  6. [...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]

  7. How do I update this to use a different database structure?

    I wish to add these select boxes:
    - Product Name
    - Size
    - Material
    - Color
    - Collar

    I get a problem when I try to populate the Material options as follows:

    If the user selected PRODUCT: AA1, SIZE: large then it should show MATERIAL options of: silk, cotton. However, this database structure forces me to input all possible options for SIZE: large, meaning that it shows all SIZE: large material options even for products that do not actually have that material available. (AA1 may have silk available in large, but BB1 does not have silk available in large).

    In other words: the options in box3 should be determined by the selection in box 1+2. However with this database structure the options in box3 are determined by box2, ignoring the selection in box1.

    1) How should we update the code to use a relational database structure instead of this 'one table' approach?
    2) Also I cannot get it to populate box4 (color).

  8. I'm having the same problem as mameha. I can't seem to figure out the solution at all.

  9. I found a clumsy way to do it:

    key | value
    ----------------
    AA1 | small
    AA1 | large
    AA1 small | silk
    AA1 small | cotton
    AA1 large | silk
    AA1 small silk | red
    AA1 small silk | blue
    AA1 small cotton | red
    etc...

    Its not ideal but I can live with it.

    I am now trying to change it so that box1 remains a select list, but box2 is a list of checkboxes. No idea where to start though...

  10. Hi!

    How can I pre-select an option in the second select box? Example is when the page loads, The element category pre-selected option is Scripts then the element category pre-selected option is Noscript

  11. Thanks for the great plugin! It was a real timesaver, and the best I found for what it does. And mameha, I think I had the same problem as you, that the script only sends the last changed select's value to the ajax script, so I solved the problem by tinkering a little in the script by doing this (and I'm not a professional jscript programmer.. so it might not be the best way to do it, but at least it works! Look at about line 15 to see what I changed, this should give the ajax script the values of all the selects on the form...):

    $$.change(function () {
      var data = null;
    
      $(this).parent().children("SELECT").each(function(i) {
        if (typeof settings.data == 'string') {
          data = settings.data + '&' + this.name + '=' + $(this).val();
        } else if (typeof settings.data == 'object') {
          data = settings.data;
          data[this.name] = $(this).val();
        }
      });
    });
  12. There's an error in your code on change function / default data argument. The select data aren't sent if I don't define data setting. Cause settings.data is null and don't enter the conditionals on change event.

    In my code I solve this just by putting void data on default settings:
    var defaults = {
    key: "id",
    value: "label",
    data: ""
    };

    Sorry my bad english and thanks for your code. This saves my time.

  13. [...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]

  14. Hi All!
    For pre-selected second select: http://jsbin.com/ujopi (edited by blog author avoid dumping JS inline with comments).

  15. anybody have the classic ASP equivalent to this PHP ?

  16. I'm trying to implement the eBay categories example and am having trouble with utf-8 characters (I'm using eBay Spain). The category names have accented characters that appear fine when I print them in the HTML (I have charset set to utf-8) but using your script the select boxes don't print them correctly. I'm guessing the info is screwing up in the JSON POST response, but I'm not sure how to fix it.
    Thanks! (by the way, great plugin)

  17. Hi Remy, i've got a little problem with your excellent plug-in, but only on IE, here's my code.

    profil.php (my 3 select) : http://panpan.pastebin.com/m27ca2627
    ajax.php : http://panpan.pastebin.com/m669e97d0

    I use jQuery 1.3.1 and of course your select-chain.js. Everything works perfectly on FF but on IE the select#ville is not populate but the request seems to be good and the select#departement IS populate.

    a screen of the IE debug bar :

    http://www.bandofbranleurs.com/upload/1/1234018171_2009_02_07_154912.png

    So can you watch the problem ? Thx !

  18. Thank you very much. Your article has taught me a lot.
    Actually I am planing to read and try to grasp "Auto-populating Select Boxes using jQuery & AJAX"

  19. I have found the bug, it seems that ie doesn't want to populate a select#id but works on a div#id.

    Everything is good !

    Thx again for your plugin.

  20. Hi anyone know if this it's possible to implement this without a database? I have PHP but not a db back-end.

Leave a Reply
Not required

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