jQuery controlled Dependent (or Cascading) Select List

When I was searching the web for a client side dependent list boxes, I got some scripts. But some of them were very much static (static select name, option name etc.), some were vary complex. Then I thought to make it myself.
I have been using jQuery as the standard JavaScript library for most of my web project for some days. Writing javascript coding in jQuery is fun. So here goes my contribution using it.

Here is a simple demo.

Let me guide you through it.

1. Include jqury.js.

<script language=”javascript” src=”jquery.js”></script>

You can get Jquery from here.

2. Write this simple function in a javascript block in head.

function makeSublist(parent,child,isSubselectOptional)
{
$(“body”).append(“<select style=’display:none’ id='”+parent+child+”‘></select>”);
$(‘#’+parent+child).html($(“#”+child+” option”));
$(‘#’+child).html(“<option> — </option>”);
$(‘#’+parent).change(
function()
{
var parentValue = $(‘#’+parent).attr(‘value’);
$(‘#’+child).html($(“#”+parent+child+” .sub_”+parentValue).clone());
if(isSubselectOptional) $(‘#’+child).prepend(“<option> — Select — </option>”);
}
);
}

This function takes 3 arguments: the parent select input’s id, the child select input’s id, and a boolean value to indicate whether to select an item from child list by default.

Example: makeSublist(‘listA’,’listB’,false);

This function will make the options of ‘listB’ list depending on the selection of ‘listA’. And user have to select an item from ‘listB’.
Here ‘listA’ and ‘listB’ are the IDs of parent and child select input respectively.

3. Add a class to the ‘<option>’s of the child list box. The class name will be the value of it’s parent ‘<option>’ in parent listbox with a ‘sub_’ prefix.
Suppose, in parent listbox there is an item “Flower”. Its value is ‘fl’:

<option value=’fl’>Flower</option>

When the item “Flower” will be selected, only 3 items should be visible in child listbox. These 3 items should hold the class name ‘sub_fl’:

<option class=”sub_fl” value=”1″>Rose</option>
<option class=”sub_fl” value=”2″>Sunflower</option>
<option class=”sub_fl” value=”3″>Orchid</option>

4. Now you are ready. On ‘$(document).ready’ event of Jquery, run the function to associate your list boxes.

$(document).ready(function()
{
makeSublist(‘parentID’,’childID’, false);
});

5. Enjoy 🙂

33 Comments

  1. nice function but where is the dynamic part ?? i am always in search of a such script but getting the values from the db, so it need some php works , don’t you think ??

  2. Hi Mohamed Badr,
    Thanx for ur comment.
    Here the dynamic matter is that, you can set option values from database using php and can make multiple and multilevel dependent listbox.
    You can use this simple technique to set list options from db using php:

    <select name=”parentList” id=”parentList” size=”1″>
    <option value=”none”>– Select one –</option>
    <?php
    while($row = mysql_fetch_array($result, MYSQL_BOTH))
    {
    echo “<option value=” . $row[‘optionValue’] . “>”. $row[‘optionText’] .”</option>”;
    }
    ?>
    </select>

    And for child lists :

    <select name=”childList” id=”childList” size=”1″>
    <?php
    //subItems of Man
    while($row = mysql_fetch_array($resultMan, MYSQL_BOTH))
    {
    echo “<option class=’sub_men’ value=” . $row[‘optionValue’] . “>”. $row[‘optionText’] .”</option>”;
    }
    //subItems of Woman
    while($row = mysql_fetch_array($resultWomen, MYSQL_BOTH))
    {
    echo “<option class=’sub_women’ value=” . $row[‘optionValue’] . “>”. $row[‘optionText’] .”</option>”;
    }
    ?>
    </select>

    Now your class names of child list is organised and you can use the function to make them associate. 🙂
    Thanx again.

  3. Hi Dave,
    Thanx a lot. It’s really a nice way.
    But, the problem in this technique is, a parent option without any child option is not possible here. But sometimes, we need the flexibility to use options which may have or may have not any child option.
    However, I m thinking to write another function based on this technique and automating next processes using jQuery.
    Thanx again for ur suggestion.

  4. Hi webdube,
    Its very easy 🙂

    For multiple dependent select lists :
    $(document).ready(function()
    {
    makeSublist(’parentID1’,’childID1’, false);
    makeSublist(’parentID2’,’childID2’, false);
    makeSublist(’parentID3’,’childID3’, false);
    });

    For multilevel dependent select lists :
    $(document).ready(function()
    {
    makeSublist(’selectID1’,’selectID2’, false);
    makeSublist(’selectID2’,’selectID3’, false);
    makeSublist(’selectID3’,’selectID4’, false);
    });

    Please tell me if any confusion.
    Thanks

  5. When my selection field is within a table: The code never gets fired and all child elements are displayed regardless of user input. How do I remedy this? Thanks!

  6. Hi anisniit

    if I have one parent but I have 12 childs like

    …..

    all of 12 childs must be upto 1 parent.

    Help men if you have time.
    Vilart

  7. How can you set a default selected child item upon page load? For example, onload I’d like Animal > Dog to be selected from the parent-child lists.

    Great job, btw!

  8. Hi Anis,

    I ended up altering your old script (since I didn’t know you had updated it and I needed to get it done for a project yesterday), but I was wondering if you could help me tweak it a little bit. I ended up changing it so that I can call the function “onChange” of the parent select list and also “onLoad” of the body/document. But I can’t figure out how to attach the same function to both “onChange” and “onLoad” events. Could you take a look at the code below and point me in the right direction? Any help is greatly appreciated!

    function RelateDD(parent,child,isSubselectOptional,str,val) {
    $j(“body”).append(“”);
    $j(‘#’+parent+child).html($j(“#”+child+” option”));
    $j(‘#’+child).html(“”+str+””);
    $j(‘#’+parent).change(
    function() {
    var parentValue = $j(‘#’+parent).attr(‘value’);
    $j(‘#’+child).html($j(“#”+parent+child+” .sub_”+parentValue).clone());
    if($j(‘#’+child).html().indexOf(“selected”) > -1 && val != “”) {
    $j(“#”+child+’ option[value=”‘+val+'”]’).attr(‘selected’,’selected’);
    }
    if(isSubselectOptional) {
    $j(‘#’+child).prepend(“”+str+””);
    if(val == “”) $j(“#”+child+’ option[text=”‘+str+'”]’).attr(‘selected’,’selected’);
    }
    $j(‘#’+child).focus();
    }
    );
    $j(window).load(
    function() {
    var parentValue = $j(‘#’+parent).attr(‘value’);
    $j(‘#’+child).html($j(“#”+parent+child+” .sub_”+parentValue).clone());
    if($j(‘#’+child).html().indexOf(“selected”) > -1 && val != “”) {
    $j(“#”+child+’ option[value=”‘+val+'”]’).attr(‘selected’,’selected’);
    }
    if(isSubselectOptional) {
    $j(‘#’+child).prepend(“”+str+””);
    if(val == “”) $j(“#”+child+’ option[text=”‘+str+'”]’).attr(‘selected’,’selected’);
    }
    }
    );
    }
    $j(document).ready(function() {
    RelateDD(‘ls’,’lc’,true,’All’,’1′);
    });

    Thank you!

  9. hi,
    i’m tryng this function working with two selects and fill the options with php mysql. On FF it function all right. But in IE 7 don’t execute the (child).hide(). And i find that the pointer of select is correct on the second select, but all the rest of options appears.

    do you know why. i’m became krazy.

    thanks for your work. Xiaobai.

  10. Sorry about the code. I pasted everything but somehow, some of it where lost.

    Anyway the FORM is below the end of HEAD, is that right? In the last 2 select options I applied the class = “sub_”(to what ever code).

    And the BODY part is empty?

  11. Hi, I used your code and worked great, but I have a single problem that is driving me crazy, I have the select values stored in a database, and when I load the form, I need some values to be selected by default, the parent select works fine, but for some reason the child select dosn’t load any values, and when I look at the code the select shows the values it should have, but they just don’t show. Can you help me please with something?? tks a lot.

    here is the code I use

    <option value="” >

    RubroSubMaqui();
    do{
    if ($ConsultaRubroSub[1][‘id_sub_rubro’] == $sub_rubro){
    $select = ” selected”;
    }else{
    $select = “”;
    }
    ?>
    <option class="sub_” value=””>

    Great Work

  12. Hey Oscar, i have exactly the same problem you have, and i can’t find the solution. Everything seems to be alright, but no….

    Have you got the solution?? if so, please tell me about it, i’m desperated…

    or… if anyone could help, i’ll appreciate it so much!!!

    Thanks for the code!!!
    (Sorry for my poor english)

Leave a Comment

Your email address will not be published. Required fields are marked *