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)
Introducing HTML5
I am attempting to use this for a multi value picker.
The values in the second select populated upon change, but the values seem to be "phantom" values.
When I add a function to display the values;
When I select a value in the select box #SubCodes, I am presented with an alert that says:
You selected undefined with a text label of .
Any ideas?
Quick question... What syntax highlighter are you using, or did you roll your own?
By using the followng:
$('' + j[i].Code + '').appendTo($("#PAAAFuncCodes"));
I no longer experienced the undefineds.
I am writing up an article on what I did on my blog. http://jeff.dierking.name/2008/07/14/my-first-jquery-hack/
[...] Url for Auto-populating select boxes - http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ [...]
Can anyone provide a link to a working bug free version of the tutorial above for download - thanks
@Pedro - have you tried this link: http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/ - I know it's only mentioned once at the top, but it's the superseded version.
In addition, it might help if you could explain what bugs you're seeing, so that I can check it out myself and perhaps fix it.
Hi there, I was wondering if anybody could help me out. I have been working on a new website for the company I work for and got stuck when some JavaScript worked in Firefox but not Internet Explorer. By this I guess I am half way there but have done something wrong.
Now just to give you a run down on my JavaScripts, they are virtually non-existent but despite that I take in what I am told.
The website address I am working on is:
http://www.davidstanleyredfern.com/?new
You will see straight away that an error is given, this is the error I am having problems.
The error relates to the search box at the top, when you pick a country it automatically updates the region box, this works in Firefox but because of the error in Internet Explorer this does not.
You can see the modified JavaScript relating to jquery and the error by visiting:
http://www.davidstanleyredfern.com/scripts/search_box.js
I have fixed the issue, this is important for PHP programmers who think JavaScript works like PHP.
The following JSON works:
[{optionDisplay: 'Tiranë'}]
But this does not:
[{optionDisplay: 'Tiranë'},]
Unless you check to see if j[i] is an object or not like such:
var options = '';for (var i = 0; i < j.length; i++) {
if (typeof j[i] == 'object') {
options += '' + j[i].optionDisplay + '';
}
}
[...] Auto-populating Select Boxes using jQuery & AJAXLearn how to select a category and autopopulate subcategories with jQuery. [...]
i have copied the example, but the ctlPerson list menu doesn't update???
is there any reason for this?
thanks
Thanks for this fantastic script. I've managed to get it fully working as a tool to allow a user to select their county/state and then it will pull a list of towns from a MySQL db and show them in the city/town list.
Thanks again for your great work!
[...] 17. Auto-populating Select Boxes using jQuery & AJAX [...]
[...] Auto-populating Select Boxes using jQuery & AJAX- Allow the user to select a top level category from one select box and to automatically populate the sub-category using jQuery and Ajax. [...]
This is very interesting, thanks for posting! Is there a way to have the php script echo out the html for the select options and not use JSON?
hi guys,
anyone knows how to pass a string instead of an integer to the php page?
thanks.
Can someone paste whole code or example how to use it with mysql.
Thx
@Mitja - here you go: http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/
this was very handy dude, thanks.
Remy, I notice you have a comment in the source that says:
* Aug 22, 2007 - Added option to set target options when the page loads (you may have a default value selected in the primary select that you want to "preload" options in your target)
Does that mean I can set a value that shows as "selected" in the list? Can you give me an example of the syntax for this? I'd like to return the list with a value already selected.
How would this code be altered to make the secondary selects be disabled until the selects before them are changed? Something like:
Please select first
Waiting for input above
Waiting for input above