I’ve finally gotten around to writing & releasing a jQuery plugin that allows you to create any number of related/dependent select boxes in a form. I’ve yet to find a decent solution and needed something that was fairly customizable and could retrieve data using AJAX/JSON, so here she is.
[ad code=4]
From the GitHub docs:
jQuery Related Selects is a plugin that allows you to create any number of select boxes whose options are determined upon the selected value of another. You pass an array or object of select box names, and the select boxes will depend on each other in the order in which they are passed in.
When a select box is changed an AJAX request is sent to the file specified in the onChangeLoad property, passing the selected value of each select box as parameters. For now the data must be returned in JSON format. An <option> must have a legitimate value in order to trigger the script. An <option> where the value is blank (value=””) is used for the defaultOptionText option (see below).
This script provides a high level of customization. You can set the options once for each select to use, or set the options on a select-by-select basis. You can also start your markup with pre-populated options and selected values.
Usage
A basic example. Changing the “stateID” select updates the “countyID” select and so on. The values of all four select boxes are serialized and passed to datasupplier.php, which returns data for the next select box in JSON format.
<form> <select name="stateID"> <option value="">Choose State</option> <option value="MA">Massachusetts</option> <option value="VT">Vermont</option> </select> <select name="countyID"><option value="">Choose County</option></select> <select name="townID"><option value="">Choose Town</option></select> <select name="villageID"><option value="">Choose Village</option></select> </form>
$("form").relatedSelects({ onChangeLoad: 'datasupplier.php', selects: ['stateID', 'countyID', 'townID', 'villageID'] });