erichynds

Hi, I'm Eric Hynds, a front-end website developer living outside of Boston, Massachusetts. I'm passionate about developing functional, standard-compliant, and user-friendly websites.

jQuery Related (Dependent) Selects Plugin

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.

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']
});

Options

selects

Required. An array or object of select boxes you want to be dependent. Each one will depend on each other in the order in which they are passed in. If you want to override any of the options below on a select-by-select basis you can pass this as an object. See examples.

onChangeLoad

Required. The file to call to retrieve data when a select box is changed. Data must be returned in JSON format for now.

loadingMessage

Optional. The text to change the sibling select box to during the AJAX request.

defaultOptionText

Optional. The text inside the default <option> tag after AJAX populates a select box. This is typically the text where you instruct the user to choose an option. If this option is not provided and an <option> tag with a blank value attribute exists in your markup, that text will be used.

onLoadingStart

Optional. A callback to fire when the AJAX call starts.

onLoadingEnd

Optional. A callback to fire when the AJAX call ends.

onChange

Optional. A callback to fire when a select box is changed.

11-18-2009: Bug fix & new features update

I’ve fix a bug where refreshing the page makes all selects become active, and added a new option and callback:

disableIfEmpty

Set this option to true to keep the next select disabled if the previous does not return any results.

onEmptyResult

Optional. A callback to fire when no results are returned after changing a select.

12-2-2009: Update: Return data in HTML format

Data can now be returned in HTML format by using the new dataType option. Set it to either ‘html’ or ‘json’ (default).

Related posts:

  1. jQuery Related Selects Plugin 0.3
  • http://Localhost/ miskotes

    I seems that there are some php requirements for this plugin to work.

    Wamp server on Win 7 will not load related select (PHP 5.3.0), just stay on loading, where MAMP server on Mac OSX 10.6.2 loads fine the same file (PHP 5.2.11).

    Now I checked PHP core on both servers and made sure they are identical. No joy.

    JSON is enabled.

    Are there some other settings to consider Thanks.

  • http://Localhost miskotes

    I seems that there are some php requirements for this plugin to work.

    Wamp server on Win 7 will not load related select (PHP 5.3.0), just stay on loading, where MAMP server on Mac OSX 10.6.2 loads fine the same file (PHP 5.2.11).

    Now I checked PHP core on both servers and made sure they are identical. No joy.

    JSON is enabled.

    Are there some other settings to consider Thanks.

  • Anonymous

    @miskotes, it probably isn’t able to parse the JSON returned from the server. Look @ the datasupplier.php file on the GitHub page for an example… how are you creating the JSON? Also try using Firebug to see what the response looks like.

  • http://www.erichynds.com Eric Hynds

    @miskotes, it probably isn’t able to parse the JSON returned from the server. Look @ the datasupplier.php file on the GitHub page for an example… how are you creating the JSON? Also try using Firebug to see what the response looks like.

  • http://www.mably.com/ Francois Masurel

    This is a really useful plugin, great work !

    One thing it would be nice to be able to do is to cache locally already fetched data.

    It doesn’t seem to be the case at the moment or am I wrong ?

  • http://www.mably.com Francois Masurel

    This is a really useful plugin, great work !

    One thing it would be nice to be able to do is to cache locally already fetched data.

    It doesn’t seem to be the case at the moment or am I wrong ?

  • Anonymous

    @Francois, not yet, but it is on my todo list.

  • http://www.erichynds.com Eric Hynds

    @Francois, not yet, but it is on my todo list.

  • mohammmed

    thanks man for the great work,man i was looking for something like this for a while maybe you could post a database example where you pull options from records

  • mohammmed

    thanks man for the great work,man i was looking for something like this for a while maybe you could post a database example where you pull options from records

  • http://www.erichynds.com/jquery/jquery-related-selects-0-3/ jQuery Related Selects 0.3 « Eric Hynds – Website Developer

    [...] Get in Touch Welcome to my online development portfolio. I am a website developer living in Newton, Massachusetts and am passionate about developing functional, standard-compliant, user-friendly websites. « jQuery Related (Dependent) Selects Plugin [...]

  • Jens

    Hi Eric,

    great work and thanks for sharing.
    I would like to work with selects having a size of 10.

    My problem is that if I went into level 4 and go back to level 1, level 3 and level 4 are disabled (which is correct), but I can still see the last options in these levels.

    Is there any way to remove the options from these levels?
    I hope my problem is understandable and sorry or my awful english.

  • Jens

    Hi Eric,

    great work and thanks for sharing.
    I would like to work with selects having a size of 10.

    My problem is that if I went into level 4 and go back to level 1, level 3 and level 4 are disabled (which is correct), but I can still see the last options in these levels.

    Is there any way to remove the options from these levels?
    I hope my problem is understandable and sorry or my awful english.

  • Alex

    Hi Eric,

    Your plugin is superb. Any suggestions how to populate selects using database?

    Thanks

  • Alex

    Hi Eric,

    Your plugin is superb. Any suggestions how to populate selects using database?

    Thanks

  • Anonymous

    @Jens, the default option (where the value=”", and the text typically instructs the user to select an option) in each disabled select should automatically be selected. Do you want to completely empty the select boxes?

    @Alex, set the onChangeLoad argument to a file or URL which executes a database query using your favorite server-side language. The query should retrieve some kind of ID for each option’s value attribute and text to add in between the tags. Encode the results into JSON format; your programming language probably has a method for this, like ColdFusion has jsonencode(). Print the JSON string to the browser, and you should be all set.

  • http://www.erichynds.com Eric Hynds

    @Jens, the default option (where the value=”", and the text typically instructs the user to select an option) in each disabled select should automatically be selected. Do you want to completely empty the select boxes?

    @Alex, set the onChangeLoad argument to a file or URL which executes a database query using your favorite server-side language. The query should retrieve some kind of ID for each option’s value attribute and text to add in between the tags. Encode the results into JSON format; your programming language probably has a method for this, like ColdFusion has jsonencode(). Print the JSON string to the browser, and you should be all set.

  • panos

    Hi.
    This is a very nice tutorial.Can someone post a remake datasupplier page from .php to datasupplier.cfm (using coldfusion)?

  • panos

    Hi.
    This is a very nice tutorial.Can someone post a remake datasupplier page from .php to datasupplier.cfm (using coldfusion)?

  • http://www.refillcenter.se/ Alex Voicu

    Hi,
    This is a nice plugin that works on FF, Safari and Chrome. But i have no luck on IE 8!

    Can you help me ?

    Alex

  • http://www.refillcenter.se Alex Voicu

    Hi,
    This is a nice plugin that works on FF, Safari and Chrome. But i have no luck on IE 8!

    Can you help me ?

    Alex

  • http://www.refillcenter.se/ Alex Voicu

    After MANY MANY experiments, some installing of debuggers in IE (namely Debugbar and firebug) i have now concluded that IE is a piece of crap…an abomination of this world!!

    The solution to my problem was simple, and yet so showstopping.

    I kept sending
    {“CHA”:”Chatham”,”DEN”:”Dennis”,”YAR”:”Yarmouth”,}

    in the AJAX response…Notice that last , ? The last , should not be there, IE does not understand that.

    EVERYONE else does tho…

  • http://www.refillcenter.se Alex Voicu

    After MANY MANY experiments, some installing of debuggers in IE (namely Debugbar and firebug) i have now concluded that IE is a piece of crap…an abomination of this world!!

    The solution to my problem was simple, and yet so showstopping.

    I kept sending
    {“CHA”:”Chatham”,”DEN”:”Dennis”,”YAR”:”Yarmouth”,}

    in the AJAX response…Notice that last , ? The last , should not be there, IE does not understand that.

    EVERYONE else does tho…

  • Anonymous

    Alex, yeah, I usually look for extra commas around object literals first when only IE is throwing errors… but, it sounds like IE is doing something right here because that JSON is invalid :) Also, if you’re running version 1.4, jQuery will not fire the AJAX “success” callback if it receives malformed JSON back from the server. Just something to be aware of. JSON Lint is a good JSON debugging tool for these situations.

  • http://www.erichynds.com Eric Hynds

    Alex, yeah, I usually look for extra commas around object literals first when only IE is throwing errors… but, it sounds like IE is doing something right here because that JSON is invalid :) Also, if you’re running version 1.4, jQuery will not fire the AJAX “success” callback if it receives malformed JSON back from the server. Just something to be aware of. JSON Lint is a good JSON debugging tool for these situations.

  • Alex

    Thanks for your reply.
    The least I would like IE to do is at least throw an error if the JSON structure is broken. But it does not, even with “Show Warnings on page” option turned on. Which makes developing for it a living hell.

    On a related note:
    {
    “CHA”: ”Chatham”,
    ”DEN”: ”Dennis”,
    ”YAR”: ”Yarmouth”
    }
    Will receive an error in JSON Lint. Go figure..

    Is there any other debugging tools available? I receive the same error on another call now when i try to pull _html_ via Jquery. Same as before, all other browsers work, IE doesnt..

    And this time I am pretty sure its the correct html!

    Thanks!

  • Alex

    Thanks for your reply.
    The least I would like IE to do is at least throw an error if the JSON structure is broken. But it does not, even with “Show Warnings on page” option turned on. Which makes developing for it a living hell.

    On a related note:
    {
    “CHA”: ”Chatham”,
    ”DEN”: ”Dennis”,
    ”YAR”: ”Yarmouth”
    }
    Will receive an error in JSON Lint. Go figure..

    Is there any other debugging tools available? I receive the same error on another call now when i try to pull _html_ via Jquery. Same as before, all other browsers work, IE doesnt..

    And this time I am pretty sure its the correct html!

    Thanks!

  • Alex

    Scratch my last comment. Ran my code through w3.com validator and i was missing a div…

    Thanks yet again for a very good plugin.

  • Alex

    Scratch my last comment. Ran my code through w3.com validator and i was missing a div…

    Thanks yet again for a very good plugin.

  • morowind

    First I want to thank you for your great plugin.
    I need help :
    I have 3 related listboxes (category->subcategory->subsubcategory) and I want triger 4′th listbox “type” from second listbox “subcategory”.
    How can I do this.
    Thanks

  • morowind

    First I want to thank you for your great plugin.
    I need help :
    I have 3 related listboxes (category->subcategory->subsubcategory) and I want triger 4′th listbox “type” from second listbox “subcategory”.
    How can I do this.
    Thanks

  • Anonymous

    Hi Morowind, there’s no way to do that at the moment… each select depends on the previous one in the order in which they were passed to the “selects” parameter.

  • http://www.erichynds.com Eric Hynds

    Hi Morowind, there’s no way to do that at the moment… each select depends on the previous one in the order in which they were passed to the “selects” parameter.

  • morowind

    Thank you very much .I will try some other ajax call onchange event.
    Great work anyway.

  • morowind

    Thank you very much .I will try some other ajax call onchange event.
    Great work anyway.

  • morowind

    I’m back again .
    How can I hide selectbox if ajax response or selectbox is empty or null (change disable attr) ?.
    This script doesn’t work for multiple instances in same form , or I am wrong?
    Thanks

  • morowind

    I’m back again .
    How can I hide selectbox if ajax response or selectbox is empty or null (change disable attr) ?.
    This script doesn’t work for multiple instances in same form , or I am wrong?
    Thanks

  • http://www.discsport.se/ Per

    Hi Eric!
    I’m trying to get this working with two boxes.
    Nothing happends with the second box, accept for the “Please wait..”

    From what I can tell the data-file isnt loaded:
    onChangeLoad: ‘quick_search_data.php’

    If I write a simple echo “Hello!” it should be seen on the screen if the data-file is loaded, right?

    Regards, Per
    Greetings from Sweden

  • http://www.discsport.se Per

    Hi Eric!
    I’m trying to get this working with two boxes.
    Nothing happends with the second box, accept for the “Please wait..”

    From what I can tell the data-file isnt loaded:
    onChangeLoad: ‘quick_search_data.php’

    If I write a simple echo “Hello!” it should be seen on the screen if the data-file is loaded, right?

    Regards, Per
    Greetings from Sweden

  • bufer

    Hello guys,
    Like wrote, this select doesn’t work on PHP 5.3 version, then i select first selection firebug gives me an answer

    Notice: Undefined index: countyID in C:wampwwwtestinisehynds-jquery-related-selectsdatasupplier.php on line 7

    Notice: Undefined index: townID in C:wampwwwtestinisehynds-jquery-related-selectsdatasupplier.php on line 8

    Notice: Undefined index: html in C:wampwwwtestinisehynds-jquery-related-selectsdatasupplier.php on line 9
    {“BARN”:”Barnstable”,”PLYM”:”Plymouth”}

    that means that JSON works OK, it has the values {“BARN”:”Barnstable”,”PLYM”:”Plymouth”}, but they are not shown.
    Sorry for my english :)

  • bufer

    Hello guys,
    Like wrote, this select doesn’t work on PHP 5.3 version, then i select first selection firebug gives me an answer

    Notice: Undefined index: countyID in C:\wamp\www\testinis\ehynds-jquery-related-selects\datasupplier.php on line 7

    Notice: Undefined index: townID in C:\wamp\www\testinis\ehynds-jquery-related-selects\datasupplier.php on line 8

    Notice: Undefined index: html in C:\wamp\www\testinis\ehynds-jquery-related-selects\datasupplier.php on line 9
    {“BARN”:”Barnstable”,”PLYM”:”Plymouth”}

    that means that JSON works OK, it has the values {“BARN”:”Barnstable”,”PLYM”:”Plymouth”}, but they are not shown.
    Sorry for my english :)

  • Anonymous

    Per, probably not. If you’re using JSON as the datatype, jQuery will not sure the “success” callback if the response is not valid JSON, so you won’t see anything. If you’re using HTML as the datatype, you need to return option tags back to the client.

    Bufer, that’s a PHP error. My guess is you’re tying to refer to variables that do not exist.

  • http://www.erichynds.com Eric Hynds

    Per, probably not. If you’re using JSON as the datatype, jQuery will not sure the “success” callback if the response is not valid JSON, so you won’t see anything. If you’re using HTML as the datatype, you need to return option tags back to the client.

    Bufer, that’s a PHP error. My guess is you’re tying to refer to variables that do not exist.

  • bufer

    Strange, i’ve just extracted your code, thats all, any changes, and im running wamp with php 5.3 ver. and the code doesn’t work, any hints? You are smart guy and i know there is something on your mind :)

  • bufer

    Strange, i’ve just extracted your code, thats all, any changes, and im running wamp with php 5.3 ver. and the code doesn’t work, any hints? You are smart guy and i know there is something on your mind :)

  • http://www.facebook.com/corbosman Cor Bosman

    Very useful plugin. Two feature requests if you still have time to work on this plugin:

    1) allow user to select the GET or POST method. This is pretty trivial. Ive hardcoded POST in your plugin now. This is necessary for things like codeignitor that are POST centric.

    2) allow user to add additional parameters in the ajax call. Im using your code in a place where the value of the options im returning are dependent on another parameter. I can work around it, but I think it would be useful.

  • ehynds

    Thanks for the feedback Cor. When I get a minute I'll add an “ajax options” parameter so you can pass in any of the $.ajax settings.

  • Aldo

    Hello,

    Great plugin!
    Is there a way to set the url of onChangeLoad during a onChange callback.
    I would like to format der url according the selection.

    Thanks,
    Aldo

  • Tiit

    Would be perfect if there's a connection with mysql, but still good job (Y)

  • ehynds

    Your data source can be anything you'd like. Instead of serializing an array (like in the demos), serialize a database recordset instead.

  • ehynds

    There is not, but I agree there should be better support for this. Stay tuned..

  • Anja

    Hello ,

    thank for the great plugin. But I have problems to adapt your code to an example using mysql.
    Is it possible that you can post a dump of the database and the code for the selection of your example???

  • Anja

    Hello ,

    thank for the great plugin. But I have problems to adapt your code to an example using mysql.
    Is it possible that you can post a dump of the database and the code for the selection of your example???

  • Riccardo De Contardi

    Very nice plugin, but… alas, my CMS generates the selects with square parenthesis in the name (i.e. name_[uid26] )!
    Is it possible to make it work?

    Thank you!!

  • M.

    hi Eric,
    I have a problem – I created exactly the same files like in your sample. but when I change the selected value – the child select list says “please wait..” all the time.
    How can I make that work? I am using windows 7 and Firefox& IE8.
    I really liked your plugin – and I would like to use it in the future.
    Thanks ))))

  • Hatch Media

    This code is great thanks… I just have one problem. When i use in a form and then press the submit button, the secondary field refreshes and the form validation detects it as an empty field and won't submit.

    Is there anyway i can stop the select box refreshing?

    thanks

  • Kamil

    Great plagin!

    Could you please help me with a such configuration:

    5 select list, when I choose from the first one, the rest loads option values. All 4 are dependent from the first one.

    How can it be done?

  • Profi

    Great. But it would be nice if it was possible to create the relatedSelect boxes on demand. So that there were no empty boxes.

  • http://twitter.com/tahanom Wuilliam Lacruz

    Nice plugin! But i have a problem, i need to load the page, whit the state, city, town, village, all whit the “Selected value” (it is a Update Module), how can i set a “SelectedIndex” to the selects automatically, by default.

    Tnks a lot! is too easy to use! Really nice, ;) help plz :D

  • Mark

    Very nice plugin. My question is regarding the HTML dataType. Your example only chains two selects, How can I chain multiple selects and get my select data from an HTML data source?

  • http://twitter.com/tahanom Wuilliam Lacruz

    Hi again! how can i set a Default Value for each select box by default (for an Update Module)

  • Canadaboy

    Sorry if it’s obvious and I’m simply blind, but I on a two box related select, I can easily have the first box selected to the option I want – how do I also get the second box to default to a selection of my choice? Thankyou, Stephen

  • Marinagroup

    Hi Eric,

    Thank you for the great plugin.

    I’m using the latest version with HTML instead of JSON. Everything is working perfectly fine in Firefox but doesn’t with IE 7 & 8.

    Is there an fix for that ?

    Thanks,
    Mark

  • Marinagroup

    Alex,

    Please ignore my last post about the IE 7 & 8 issue.. I was able to fix it.
    Thanks again for the superb plugin…

    Mark

  • John Bliss

    Thanks for the plugin. When I select an option in select #2, I’m getting the following error. What am I doing wrong…?

    (a || “”).replace is not a function
    http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
    Line 30

  • Brian

    Hoping someone can help, I have Country -> State -> City type example. I also have multiple fields on the page, when I do a form submit if their are errors the page returns with the responses in the input fields however the City Value of the select asks it to select again even though it was answered. Is there a way to see if the form value exists and if it does to select that response?

  • string

    Say I have a form with four selects and I don’t want them all chained together using your plugin. When I change select #1, I want content to load into select #2. When I change select #3, I want content to load into select #4. Selects #1 and #2 are totally unrelated to selects #3 and #4. How can this be done?

  • MikePQ

    Hi,

    Thank-you for the plugin.

    I have a small issue. If I try to use the non min version I get
    key is not defined.

    The min version shows as 1.0 while the non min version is 1.1

    Thanks
    Mike

  • Superperu

    Hi Wuilliam, did you find a solution? I ‘ve got the same problem.

  • KevinM

    @MikePQ:

    Not sure if you found it, but on the github under issues someone posted the fix:

    $.each(opts.selects, function(){ selects.push(key);
    });

    should be

    $.each(opts.selects, function(key){ selects.push(key);
    });

  • iMaxEst

    Hi! Very useful script, but I have a question: How can I setup more, then one chained selections in one form? Problem is, that script oparates by form ID, and I can’t find the solution…

  • iMaxEst

    I found the solution: just calling duplicates…

  • thecrumb

    iMaxEst – care to post your solution? I have the same issue?

  • Johnmarkinson

    Cool plugin. Only downside: the web service parameter names MUST match the web form select names.

    This causes a problem if your web service is more generalized (ie. for use by more than one app) or if you are using something like ASP.NET where the names of the fields vary by their naming container on the page.

    A “dirty” solution to the problem would be to pass in an optional second array of parameter names in the same order as the selects.

  • Moxerian

    This plug-in is so damn cool. Thanks a lot bro…

  • Anonymous

    Looks like an nice plugin but how can I change this so I can use my database?
    $states = array();
    $states['1'] = “Massachusetts”;
    $states['2'] = “Vermont”;
    $states['3'] = “South Carolina”;

  • http://twitter.com/anandkaran Karan Anand

    I think your plugin is in conflict with the validation plugin here http://bassistance.de/jquery-plugins/jquery-plugin-validation/

    just by including the script breaks the related select and I see” loading, please wait..” on the dependent select menu. Can you check and confirm. or tell a possible solution