Auto-populating Select Boxes using jQuery & AJAX
Update: due to popular demand, I've caved in, and written a plugin and demos with multiple-select boxes populating each other and driven from MySQL.
If you are familiar with using select boxes for categorisation and sub-categories, such as ebay does when selling an item, usually this can require a lot of JavaScript to maintain the select boxes, but jQuery can hugely simplify this task by adding a dash of AJAX.
The Goal
Allow the user to select a top level category from one select box and to automatically populate the sub-category.
Prerequisites
- Latest copy of jQuery
- A basic understanding of JSON (don’t let this put you off - it’s really very, very easy)
- A server-side script that can respond to the AJAX request (though I’ve provided a simple example)
Demo
Our demo will specifically look to build a simple form that allows us to book human resource for a project. The top level category is the resource type, and the sub-category will list the individual’s names.
How it works
Once the top level category select is changed, it sends an AJAX request for the sub-categories. The result of which are converted to select options and the sub-category select’s elements are replaced.
Unobtrusive JavaScript
First things first: as with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.
To achieve this for our tutorial here’s what we need to ensure:
- When the page is loaded, the sub-category is loaded (if the top level has a selected item).
- There is a ‘load sub-category’ button the user can select to re-load the page. We will hide this button with a <noscript> tag in our demo.
The Code
There are 4 parts to this demo.
- The page’s HTML.
- The server-side code to produce the dynamic page (i.e. to pre-load the select boxes when the user first visits).
- The jQuery & JavaScript.
- The JSON response (which will reuse the server-side code).
HTML
<form action="/select_demo.php">
<label for="ctlJob">Job Function:</label>
<select name="id" id="ctlJob">
<option value="1">Managers</option>
<option value="2">Team Leaders</option>
<option value="3">Developers</option>
</select>
<noscript>
<input type="submit" name="action" value="Load Individuals" />
</noscript>
<label for="ctlPerson">Individual:</label>
<select name="person_id" id="ctlPerson">
<option value="1">Mark P</option>
<option value="2">Andy Y</option>
<option value="3">Richard B</option>
</select>
<input type="submit" name="action" value="Book" />
</form>
Server-side
This is just a simple example, but it should be obvious that you can expand this to go off to a database and return an object in a JSON data structure:
<?php
if ($_GET['id'] == 1) {
echo <<<HERE_DOC
[ {"optionValue": 0, "optionDisplay": "Mark"}, {"optionValue":1, "optionDisplay": "Andy"}, {"optionValue":2, "optionDisplay": "Richard"}]
HERE_DOC;
} else if ($_GET['id'] == 2) {
echo <<<HERE_DOC
[{"optionValue":10, "optionDisplay": "Remy"}, {"optionValue":11, "optionDisplay": "Arif"}, {"optionValue":12, "optionDisplay": "JC"}]
HERE_DOC;
} else if ($_GET['id'] == 3) {
echo <<<HERE_DOC
[{"optionValue":20, "optionDisplay": "Aidan"}, {"optionValue":21, "optionDisplay":"Russell"}]
HERE_DOC;
}
?>
Note that this is not accessible. To ensure accessibility, the server side will handle the pre-population of the select boxes as the page is loaded. Here is an example (excluding the headers, footers and JavaScript) of the accessible example.
JSON Response
If I pass the server side id = 2, i.e. /select.php?id=2&ajax=true, the return value is (the ajax=true is an arbitrary flag that I’m using to differentiate between a normal user request and one done via AJAX):
[ {"optionValue":10, "optionDisplay": "Remy"},
{"optionValue":11, "optionDisplay": "Arif"},
{"optionValue":12, "optionDisplay": "JC"}]
The enclosing square brackets denotes an array and each element is separated by a comma.
Within the array are three objects. If you’re familiar with PHP or Perl, you can basically treat these as hashes. The objects have keys (in this case two keys, one called ‘optionValue’ and one called ‘optionDisplay’), and values. Note that keys don’t need to be wrapped in quotes (though in some cases you will need them sometimes).
There are two ways which we can get the data out of this structure (assuming j is the structure):
alert(j['optionDisplay'])
Or:
alert(j.optionDisplay)
jQuery & AJAX Request
Our JavaScript is going to attach itself after the page is load, and fire an event each time the job function select box is changed.
The event will send the new value of the select box and reload the contents of the person select box.
Note that I’m be a bit naughty here, in that I’m plugging HTML directly in to the DOM.
Each item in the JSON response is looped round and used to build up the new options for the select box. As the response is an array (as mentioned earlier), we can call the .length method on it.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#ctlPerson").html(options);
})
})
})
</script>
Where to take it next
So that’s the primer. Next steps: upgrade, integrate, extend and stylise. Below is an example of the category selection when submitting an item for sale on Ebay.

It should be a simple next step to integrate a database behind the selection methods and create more complicated selection like this Ebay example.
Let me know if you spot any glaring errors or have any comments.
You should follow me on Twitter here I'll tweet about JavaScript, HTML 5 and other such gems (amongst usual tweet-splurges)


Has anyone done this with multiple mysql tables? I am trying to use this for localities and my Countries, States, Cities are all in separate tables. I need the states to populate based on the country chosen and then cities populated after state is chosen.
Remy Sharp thx you very much!
[...] Auto Populating Select Boxes Using jQuery and AJAX Learn how to allow users to choose a top-level category in a select box that will trigger the subcategory box to autopopulate. [...]
[...] Auto Populating Select Boxes Using jQuery and AJAX Learn how to allow users to choose a top-level category in a select box that will trigger the subcategory box to autopopulate. [...]
[...] Auto Populating Select Boxes Using jQuery and AJAX Learn how to allow users to choose a top-level category in a select box that will trigger the subcategory box to autopopulate. [...]
[...] Auto Populating Select Boxes Using jQuery and AJAXLearn how to allow users to choose a top-level category in a select box that will trigger the subcategory box to autopopulate. [...]
[...] Auto Populating Select Boxes Using jQuery and AJAX Learn how to allow users to choose a top-level category in a select box that will trigger the subcategory box to autopopulate. [...]
[...] Auto Populating Select Boxes Using jQuery and AJAX Learn how to allow users to choose a top-level category in a select box that will trigger the subcategory box to autopopulate. [...]
This codes not work in internet explorer 7,8
not work in ie 7-8, but work in firefox
Hi Remy,
Great work on this script!
i am trying to do something different / Possible simple using some of your script.
I am creating a Search box for a website and the user will have the option to select from the dropdown list to add filter to search.
Issue:
i am trying to get this script to work that when an item is selected from the list e.g "cars" it will then populate a text field with text associated with the item selected e.g searching "all cars" and display it in the text field
so the bottom line, i would like to use a dropdown menu and a textfield instead of two dropdowns?
Can you help or are you as confused as me
thanks for the tutorial - its great that you kept it so basic just covering the fundamentals so I could use it for what I needed
I am having a terrible time getting this to work. Did I miss something?
Help? seems as tho its ignoring the select completly
If anyone has got this to work, please contact me at dsmith69 at swbell.net
Nothing appears wrong but the Person list never changes.
I don't know if it is a bug or not, but when you choose, let's say option #2, which is 'Lead Dev'. 'Remy' and others appear in the sub option. Now, when you refresh the page, the second option goes back to its original position but the first one doesn't. Any way to fix it?
Well didnt get any reponse here but I got it figured out, I was confused by the same code above, but it worked out.
Have it now populating the boxes from MySQL data. Works great.
This is incredible. Thank you!
Marty - hopefully this helps you.
I am using this for chained select statements. I have 3. I tweaked the code a bit. I set the 2nd and 3rd selects to disabled and when the 1st is changed then i set the 2nd to not disabled and set the data from a mysql database. Then basically copied the code for the 2nd on change.
here is a snippet of the code i added
//enable 2nd, keep 3rd disabled incase 3rd was enabled after 2nd may have been changed.
$("#rsecond").removeAttr("disabled");
$("#third").attr("disabled", 'disabled');
then in the changing of the 2nd i added code to allow the 3rd to be enabled.
thanks again!
Hi Remy, great example for jQuery noob like me. Thanks
Hi Remy,
Any way to do the same but from radio to select list? So if user selects option A from radio button, then certain values are auto-populated, if B other values are auto-populated and so on ...
Hi Remy, is this possible from a radio button choice auto-populating a select list?
You could use the PHP-function
json_encode()for the array.http://be2.php.net/json_encode
Here is a question for Remy or anyone regarding this solution. How do you dynamically update/populate a THIRD drop-down based on whatever user selects on the first drop-down? So far this example shows up to two drop-downs. I know there is a solution for this with mysql but I don't have access to that (only PHP), so I was wondering if anyone had suggestions on how to tweak this code to update a third drop-down ... I'm trying but no luck so far ...
Please I need help with this example but with use of mysql database
This code does not work with IE6. Please provide a version that does. Thanks.
I, too would like a db solution to this. This looks like an awesome script. What I would like to see is something that allows a user to select an item from a pull-down menu and then have it query the mysql db, fille out the form with the values from the db.
I love this sample. What if the data is in the xml file? how do we do? Any tips will be appreciated. here is my xml file.
math
1:00pm
3:00pm
physic
1:00pm
3:00pm
I rarely leave comments on posts but this post is definitely an exception. I was able to get my select boxes auto loading with your example in literally less than 5 minutes.
THANK YOU!!!
As a side note to readers, I would like to emphasize the importance of keeping the script which returns the JSON as small as possible. In other words, if you have a main index file which processes everything and includes everything under the sun, you will want to create a separate script just for JSON tasks so that your output gets back as soon as possible. This may be obvious but I've seen developers who run everything through a massive main script and then they wonder why their boxes are loading slow.
has anyone done anything that the ebay selection example given at the end of this article. I need something similar to that. It would be nice to start where someone else left off
thanks.
Thanks a lot ! I was looking for something like your selectboxes .... BUT i'm new at all this and wonder if U can help me out. I don't know where to put all the codes !
Html's part is ok but I don't know how to use the rest ????? For a simple use without database do I need to use all the 4 parts ? I'd be very interesting in a response and hope u'll be able to do so. Thanks in advance.
A beguinner who wants to learn !
It can be very slow!!!
You have to use jquery function replaceWith instead of html.
This is the fastest way because you wrap everything in a single element when doing any kind of DOM insertion. For more info read 7th tip of http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip7.
Consider my example guys. My form contains 3 text fields. It's connected to a mysql database with 3 corresponding fields. Once a user enters a value in the 1st field, and then presses the tab key, or changes focus to the 2nd field with a mouse, fields 2 and 3 are automatically populated with values that are in the same row as the value of field 1 in the database. I hope you understand my question. How can I do this? Any tutorials?
To get selectIndex of SELECT (list) using jQuery
Jquery selectedindex
Need to remember that JQuery returns an array of matching elements, even if you use the '#' selector that returns only one elements based on the ID.
So to find the selectedIndex of a list:
function Method() {
var index = $('#myList')[0].selectedIndex;
};
Thanks for this.
I have been looking everywhere for how to set an option in a select box with jquery. I couldnt see it anywhere on the Jquery site - and others..
To help anyone else who needs to do this, the code
$("select#ctlJob").attr("value","1");
Assuming you have an option in your select with value=1, this will set it to that option.
I'm trying to use this in a Drupal environment (6.13), and with no experience with ajax, though I've used many jquery plugins. The child select is just not showing up at all (unless I comment out either the plugin or the local function).
Here is the jquery I'm using to call the plugin:
$(document).ready(function() { var sp = $('#specific-select'); $('#general-select').selectChain({ target: sp, url: 'http://dev1.theportalusa.org/sites/dev1.theportalusa.org/modules/role_reg/select-chain.php', data: { ajax: true } }).trigger('change'); });I also tried getting rid of the document ready since it wasn't in the example.
Here is the test code I'm using in the php file, though I will use a database select when the rest is working:
$json[0] = '"' . 'first value' . '"'; $json[1] = '"' . 'second value' . '"'; echo '[' . implode(',', $json) . ']';Any help appreciated.
Simple, effective and objective! Congratulations, and thanks for the post. It helps me a lot.
I've downloaded your code from
http://remysharp.com/wp-content/uploads/2007/01/select.php.txtand put in the header$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '' + j[i].optionDisplay + '';
}
$("select#ctlPerson").html(options);
})
})
})
and nothing happens. The problem seems to be at
$.getJSON("select.php",{id: $(this).val(), ajax: 'true'}, function(j). $.getJSON doesn't return anything. Any help pls?Hi, I want to do something like this: http://bit.ly/1ocI0X , can anyone help me with any hints? thanks. thepanchi, where? at google mail. thx.
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({
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 from Remy et. all. will be greatly appreciated
Any help guys. I really NEED this tip. I'm at a stand still since everything else depends on this one little hiccup. I know its something small but i just cant figure it out.
Thanks,
I coded follow remy but i can not print values into the second combo box although i alert(j[i].optionDisplay) ok. I don't know why? Please help me. (using FireFox)
If you guys want to know how to use a mysql database to populate a drop down menu or need to figure out how to populate a third drop down menu based off the second drop down menu the visit this website:
http://roshanbh.com.np/2008/01/populate-triple-drop-down-list-change-options-value-from-database-using-ajax-and-php.html
If you look at it please explain what he is doing in the last part of findstate.php I have no clue if he is creating a 2nd state drop down menu or not. I am lost at that part.
Hi,
This module is exactly what I'm looking for, however my JQuery knowledge is weak.
I have things working to the point where I can click something in box 1 and box 2 gets populated with the correct number of options, but all the options say "undefined".
This is what the JSON object looks like that I'm sending back - any idea?
[{"optionDisplay":"2009-10-27","optionValue":"2009-10-27"},{"optionDisplay":"2009-10-13","optionValue":"2009-10-13"},{"optionDisplay":"2009-10-07","optionValue":"2009-10-07"}]TIA!!
this menu is great on MOZILA BUT with IE it doesn't work.. any solution??
Hey,
You are a great developer.
Thanks so much. As I don't want to use plugin(s) for "JSON select options", I found this code really helpful:
for (var i = 0; i < j.length; i++) {
options += '' + j[i].optionDisplay + '';
}
$("select#ctlPerson").html(options);
Again, thanks man!
Hello!
I have a problem and i hope you could help me because i need to finish my project and i am a little late :).
When i use this "auto-populating" method with "jqTransform (http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/)" the "auto-populating" doesn't work.
I really appreciate any help. Thanks a lot
Hi
i was hoping someone could assist me witha slight problem i have. i'm attempting to convert this method to use an ASP server side scrip[t instead of PHP and as yet have struck out.
i have simpley placed the following code in my body tags
and this give me the same response as the php test when i browse to it and manually set the id. and when using the html page it get NO java script error it just dosnt populat the boxes.
I hope some can shed some light as its probably something really simple that i'm missing
thank You in advance
i need help parsing this jason using jquery.
I have great dificulty.
I made static html page with jason so use that as a request heare is the jason i need to iterate all the elememtns on the jason.
thanks,
"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sample 2",
"author": "author 2"
}
]
Here's a bug with the latest version of JQuery is 1.4.1
this aint working in no version of ie, 6,7,8
you dont have idea how to do it, fix it, otherwise dont post articles, ive spent 3 days with it without results
i found out the solution to why it doesnt work in IE, who want it urgently mail me to fantomx1@gmail.com
for very small fee i will share it to you
You're asking a fee??? Damn that's sad
Here you go guys, this code should work:
Uhm, dunno, probably this system strips tags that I put..
$('#select2').append('option value="'+item.id+'"'+item.value+'/option');
Add brackets to form html tags in the line above
The json may look like this:
By the way, PHP can convert arrays to json, you need json php module for that.
The function is json_encode()