nav-left cat-right
cat-right

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 :)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Wists
  • Furl
  • Ma.gnolia
  • NewsVine
  • Reddit
  • Simpy
  • StumbleUpon
  • Technorati


29 Responses to “jQuery controlled Dependent (or Cascading) Select List”

  1. hasin BANGLADESH says:

    Start of a new epic, finally!!

    Welcome to the wonderful world of bloggers.

  2. Tarek BANGLADESH says:

    Nice. It’s a great work…I hope u will do more for helping us…

    keep it up..

  3. Mohamed Badr SAUDI ARABIA says:

    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 ??

  4. murad UNITED KINGDOM says:

    Well done! Keep it up.
    Murad.uk

  5. anisniit BANGLADESH says:

    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.

  6. Dave UNITED KINGDOM says:

    Perhaps a more semantic way to do this would be with optgroups? You shouldn’t need to do much with IDs then. This would convert 1 select box with multiple sub-options into 2 select boxes as you have done.

    Have a look at http://www.wait-till-i.com/index.php?p=411

    Should be easy to convert that to JQuery.

  7. anisniit BANGLADESH says:

    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.

  8. webdude UNITED KINGDOM says:

    How would you add a third or forth select option.

  9. anisniit BANGLADESH says:

    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

  10. IkMoon BANGLADESH says:

    superb logo! i really love it
    http://www.funbangla.com

  11. Visitor999 UNITED STATES says:

    I have visited your site 713-times

  12. [...] details instruction and example of using this script, please visit the previous version. Feel free to ask me if any problem with using this script or any bug you found. Share and Enjoy: [...]

  13. to_ FRANCE says:

    great but, why don’t implement it as a jQuery plugin?

  14. Morma UNITED STATES says:

    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!

  15. oscar CHILE says:

    Gracias !!! muy fácil, ya me estaba complicando con otros tutoriales.

    :)

  16. hisolart THAILAND says:

    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

  17. Pablo UNITED STATES says:

    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!

  18. Anis Ahmad HONG KONG says:

    @Pablo

    Hi friend,
    Here is the updated version of this script. It has option to mention a selected value for child select box.

    Thanks.

    http://www.ajaxray.com/blog/2007/11/08/jquery-controlled-dependent-or-cascading-select-list-2/

  19. Pablo UNITED STATES says:

    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’).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’).attr(’selected’,’selected’);
    }
    }
    );
    }
    $j(document).ready(function() {
    RelateDD(’ls’,'lc’,true,’All’,'1′);
    });

    Thank you!

  20. Xiaobai SPAIN says:

    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.

  21. Jumoke UNITED STATES says:

    i dont usually comment, but after reading through so much info i had to say thanks

  22. Justin UNITED STATES says:

    This was really handy. Thanks.

  23. JunReyes PHILIPPINES says:

    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?

  24. Oscar COLOMBIA says:

    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

  25. JR Chew UNITED STATES says:

    Great post man, saved me!

  26. Majo says:

    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 Reply