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. Thanks for this plugin ! it saves me a lot of time !

  2. How can I assing the default 'elementSelect' ?
    Best regards and thank you for this great plugin.

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

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

    $postgis_result=pg_query("select species from scarabeidos where genus='".strtolower(pg_escape_string(strip_tags($_REQUEST['genus'])))."'");
    
    $json = array();
    
    while (is_resource($postgis_result) && $row = pg_fetch_array($postgis_result)) {
      $json[] = '"' . $row->label . '"';
    }
    
    echo '[' . implode(',', $json) . ']';
    die();
    
  5. [...] Select List. Multiple Selects. Select box manipulation. Select Combo Plugin. jQuery - LinkedSelect Auto-populate multiple select boxes. Choose Plugin (Select [...]

  6. @pere - first things first, I would ensure the query is returning results. I normally do this by:

    user_error($sql)

    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.

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

    
    --- select_chain.js    2007-12-07 14:42:05.000000000 +0100
    +++ jquery_select.js    2007-12-07 14:01:10.000000000 +0100
    @@ -30,18 +30,15 @@
                         dataType: 'json',
                         success: function (j) {
    
                             var options = [], i = 0;
    
    +
    +
                             for (i = 0; i < j.length; i++) {
    -                            if (typeof j[i] == 'object') {
    -                                options.push('' + j[i][settings.value] + '');
    -                            } else if (typeof j[i] == 'string') {
    -                                options.push('' + j[i] + '');
    -                            }
    +                           var o=document.createElement("OPTION");
    +                           o.value=typeof j[i] == 'object' ? j[i][settings.key] : j[i];
    +                           o.text= typeof j[i] == 'object' ? j[i][settings.value] : j[i] ;
    +                           document.getElementById('entity').options[i]=o;
                             }
    
    -                        settings.target
    -                            .html(options.join(''))
    
                    // hand control back to browser for a moment
                    setTimeout(function () {
                        settings.target
    @@ -60,4 +57,3 @@
         });
     };
    
     })(jQuery);
  8. well hum .... this should be more readable :

    http://corpo.julbox.net/jquery_select.js

  9. [...] Auto-populate multiple select boxesLanuch Demo/site [...]

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

  11. Remy,
    I solved the question like this; thanks.

    $data = array();
    
    while ($row = pg_fetch_array($postgis_result, NULL, PGSQL_ASSOC))
    {
      $data[] = $row['the_field_I_get'];
    }
    $info = $json->encode($data);
    echo $info;
    die()
  12. 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 :)

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

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

  15. [...] Auto-populate multiple select boxes. [...]

  16. [...] Select List.Multiple Selects.Select box manipulation.Select Combo Plugin.jQuery - LinkedSelectAuto-populate multiple select boxes.Choose Plugin (Select Replacement). 表单基本、输入框、选择框等(Form Basics, Input [...]

  17. This is great, I'll implement it now and give the URL, so people have another example

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

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

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

Leave a Reply
Not required

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