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.

128 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 [...]

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

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

    
     if ($connected) {
     $sql='select * from $table where".$ID. "="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"';
    $results = mysql_query($sql);
    $json = array();
    
         while (is_resource($results) && $row = mysql_fetch_object($results)) {
             $json[] = '"' . $row->$Data . '"';
          $table = "PARTS";
          $ID = "ModelID";
          $DATA = "Year";
       }
    
          // if connected
           echo '[' . implode(',', $json) . ']';
        die(); // filthy exit, but does fine for our example.
    }
    else
    {user_error("Failed to select the database");echo "Not connected";}
    }  // end Ajax?>
    
  23. 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

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

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

  26. How can I modify this to work with coldfusion5 and MsSQL?

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

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

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

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

  31. [...] Select List.Multiple Selects.Select box manipulation.Select Combo Plugin.jQuery - LinkedSelectAuto-populate multiple select boxes.Choose Plugin (Select [...]

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

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

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

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

  36. {"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!

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

  38. @HJ - do you have a link to an example what you're talking about?

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

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

  41. Is there a way to add a static object to the selection list?
    like "No Screen" for a computer build.

  42. Hello Remy, did you read my question ?
    Thanks a lot if you have a solution.

    Have a nice day.
    Usai.d

  43. error: function (xhr, desc, er) {
      // add whatever debug you want here.
      alert("an error occurred");
    }

    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!

  44. @Haja - if you provide a link to an example then someone might be able to help.

    Otherwise, you can do one of two things:

    1. Viewing in Firefox, add the following code above the alert: console.log(arguments);
    2. Have a look at the output of your Ajax URL in Firefox. It's likely this is breaking the success function and bombing out.
  45. How to preselect values ?

  46. @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:

    <b>Warning</b>:  mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Access
    
    denied for user 'root'@'localhost' (using password: NO) in <b>/home/madhatca/public_html/neighborship
    
    .com/select-chain.php</b> on line <b>4</b><br />
    
    <br />
    
    <b>Fatal error</b>:  Connect failed - Access denied for user 'root'@'localhost' (using password: NO)
    
    in <b>/home/madhatca/public_html/neighborship.com/select-chain.php</b> on line <b>6</b><br />
  47. 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!

  48. Peter Pottinger May 9th, 2008 at 6:28 pm

    Ok well to pre-select an option here is some pseudo-code I tested
    inside the for loop add

    o.selected = true

  49. @Peter was that for me?

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

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

  52. @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:

    ['Baiji', 'western gorilla', 'sumatran']

    Or:

    type.selectChain({
      target: sp,
      url: 'request_processor.cfm',
      type: 'post',
      key: 'id',
      value: 'text',
      data: { ajax: true }
    }).trigger('change');

    With JSON as:

    [ { id: 1, text: "Cat" }, { id: 2, text: "Dog" }, { id: 3, text: "Worm"} ]
  53. 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.

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

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

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

  57. Hello! Great work!

    How do i can select on view special option from request by ID ?

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

  59. First off: many, many thanks for this plugin. I am working with Coldfusion 8 and it's implementation of doing AJAX select-box population is crap IMO, so I went back to my good ole' friend jQuery.

    I am by no means a JS / jQuery expert, so I am not sure if this is a new thing, but I think I found a bug in your code. When trying to set my own options for "key" and "value" I found that the plugin was not using them and reverting to it's own defaults no matter what.

    I reversed the order in your local settings variable per this website's suggestion (http://www.learningjquery.com/2007/10/a-plugin-development-pattern) and it seems to be working.

    old code:
    var settings = $.extend({}, options, defaults);
    new code:
    var settings = $.extend({}, defaults, options);

    Disclaimer: I'm using jQuery 1.2.6

    Thanks again for your work!

  60. @Chief - good spot! I've swapped those around now so the defaults don't override.

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

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

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

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

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

  66. [...] View: Auto-populate multiple select boxes [...]

  67. What could be the reason that my multiple select box works with Firefox but not IE7? Thanks for any suggestion!

  68. Remy, are you plan to add cache ability of results ?

  69. Remy, are you plan to add in script cache ability function for request results?

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

  71. Hi Remy,

    Very nice - this plugin will save me a lot of time. I have one question that I am not able to figure out:

    In your example with the Category->Element->Attributes boxes - how would I have the "Element" select box send the selected Category along with the selected Element?

    For example, if you pick a category of "Scripts" and then an Element of "Script" I would like the AJAX request to the server to contain the Element Category of "Scripts" and the Element of "Script", so that the server can lookup against the database where element_category='Scripts' and element='Script'.

    Maybe your example isn't the best place for functionality like that. Maybe a better example data-wise would be the first SelectBox is City, the second is Street Name, and the final result SelectBox would be House Number. In order to get the list of House Numbers, you would have to know the Street Name and the City. It wouldn't work just to pass the street name to the server, because there are multiple cities that could have the same street name. So on selecting the street name, I would like the data passed to the server to contain the city name (previously selected) and the street name that was just selected.

    Not sure if that makes sense?

    I've tried setting an event when the first select box is selected to somehow re-create the "selectChain" for the second select box to include the data from the first box in the call of the second box, but it doesn't seem like a good method.

    Not sure if this is possible, but if you have an easy solution I would sure appreciate a nudge in the right direction.

    Thanks in advance!

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

  73. Remy,
    Thanks for the code. I also have a similar need to Brian with sending multiple variables for the database to check against.

    I have an additional request too...In my page, some of my select boxes do 2 things - 1. populate the elements in another select box, 2. update another div tag with a picture of the chosen item.

    E.g. Select box "vehicle" lists a bunch of different vehicles and on selecting, a picture of the chosen vehicle appears somewhere on the page, and then select box "model" lists the models based on the vehicle chosen in the 1st select box.

    I do have another ajax script that works, but I much prefer the way your script updates the select boxes over my existing script.

    Any pointers would be greatly appreciated!

  74. [...] Auto-populate multiple select boxesA plugin to autopopulate select boxes. [...]

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

  76. This isn't working for me when I test in IE6 (using the most recent JQuery: jquery-1.2.6.min.js ). Am I missing something?

    It's not populating the boxes and it's throwing an error (even on your demonstration page):
    Line 28 / Char: 5259 / Error: Automation server can't create object

    Is this not supported on IE6? This is a great post and I had already started implementing a version of this before testing in IE6, if there is a workaround or if i'm missing something please let me know, thanks!

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

  78. would you help me with my database structure , i couldn't implement the script using my current setup.

    CREATE TABLE IF NOT EXISTS `events` (
      `cid` int(5) NOT NULL,
      `event` varchar(30) NOT NULL,
      `round` varchar(30) NOT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
    
    INSERT INTO `events` (`cid`, `event`, `round`) VALUES
    (2, 'Box 3x3x3','Second Round'),
    (2, 'Box 3x3x3','First Round'),
    (2, 'Box 3x3x3','Final Round'),
    (2, 'Box 5x5x5','Combined Final'),
    (2, 'Box 2x2x2','First Round'),
    (2, 'Box 2x2x2','Final Round'),
    (3, 'Box 2x2x2','First Round'),
    (3, 'Box 2x2x2','Second Round'),
    (3, 'Box 2x2x2','Final Round'),
    (3, 'Box 1x1x1','First Round'),
    (3, 'Box 1x1x1','Pre-Final Round'),
    (3, 'Box 1x1x1','Final Round'),
    (4, 'Box 1x1x1','Final Round'),
    (4, 'Box 1x1x1','First Round'),
    (4, 'Box 1x1x1','Second Round'),
    (4, 'Box 1x1x1','Last Round'),
    (4, 'Box 1x1x1','Combined Final');

    I'm new to jQuery and I just can't hardly modify the code to fit my setup.


  79. $(function () {
    var province= $('#fprovince_id');
    var amphur= $('#famphur_id');
    var tumbol= $('#ftumbol_id');
    amphur.selectChain({
    target: tumbol
    ,url: "../plus/district_json.cfm"
    ,type: 'post'
    ,data:{fdistrict:'tumbon'}
    });
    province.selectChain({
    target: amphur
    ,url: "../plus/district_json.cfm"
    ,type: "post"
    ,data: {fdistrict:'ampher'}
    }).trigger('change');
    });

    in step 2 (when change famphur_id) ie6 and ie7 it don't send fprovince_id value (work on firefox 3.1) you can see mistake line? i use jquery 1.2.6

  80. Can anybody give me an example of how to add the id as the value of the select box? like:

    option value="1"

    I've been trying, but no luck. Thanks for any help.

  81. @Justin

    Here's what I did.

    If I have select Box A that populates Box B:


    src_sys.change(function() {
    A.selectChain({
    target: B,
    url: '/cgi-bin/script.pl',
    type: 'get',
    key: 'id',
    value: 'name'
    });

    I have my "script.pl" script return JSON like this:

    [{id: 1, name: "ONE"},{id: 2, name: "TWO"},{id: 3, file_name: "THREE"}]

    The select (B) turns out like this:

    
    
    	
    	
    	
    
    
  82. Hmm - it took out my "select" and "option" tags...

    Basically, the id of the first option is 1, and the text is ONE, and so on....

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

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

  85. Hi,

    thanks for excellent work! It works like a charm!
    One minor bugfix, it should be:
    setTimeout(function () {
    settings.target.find('option:first')
    .attr('selected', 'selected')
    .parent('select');
    settings.target.trigger('change');
    }, 0)

    because if you chain the trigger method, and you have no options in any of the select boxes from ajax, then the trigger will not occur and we want it to clear all the rest of boxes, don't we? :)

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

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

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

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

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

  91. [...] Rellenar automáticamente Selects Múltiples [...]

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

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

  94. Hi Remy,

    Is there any way to add a callback function? If not, consider this a feature request :)

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

  96. hi, is there a way to show an icon while script is loading data?

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

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

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

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

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

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

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

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

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

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

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

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

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

  110. 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();
        }
      });
    });
  111. 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.

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

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

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

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

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

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

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

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

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

  121. Hi,

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

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

  123. Hey! Great plugin.

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

    Thanks!

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

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

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

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

Leave a Reply
Not required

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