Select Box Change Dependent Options dynamically

We may have seen different examples showing how to change/load the content in child Select Box, depending on the parent Select Box options. Most examples uses database and Ajax to achieve the same, which I think is bit unnecessary. Here’s how we can easily create dynamic dependent select box just using jQuery.

Select Box Change Dynamically

Create Array

First thing to do is to create as many arrays you need for the child select box, values from the arrays will be loaded into child select box when user selects parent select box options.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var chocolates = [
    {display: "Dark chocolate", value: "dark-chocolate" },
    {display: "Milk chocolate", value: "milk-chocolate" },
    {display: "White chocolate", value: "white-chocolate" },
    {display: "Gianduja chocolate", value: "gianduja-chocolate" }];
   
var vegetables = [
    {display: "Broccoli", value: "broccoli" },
    {display: "Cabbage", value: "cabbage" },
    {display: "Carrot", value: "carrot" },
    {display: "Cauliflower", value: "cauliflower" }];
   
var icecreams = [
    {display: "Frozen yogurt", value: "frozen-yogurt" },
    {display: "Booza", value: "booza" },
    {display: "Frozen yogurt", value: "frozen-yogurt" },
    {display: "Ice milk", value: "ice-milk" }];

On Parent Change

On parent option change, we just switch to selected text and load the associated array into child select box.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$("#parent_selection").change(function() {
    var parent = $(this).val();
    switch(parent){
        case 'chocolates':
             list(chocolates);
            break;
        case 'vegetables':
             list(vegetables);
            break;             
        case 'icecreams':
             list(icecreams);
            break; 
        default: //default child option is blank
            $("#child_selection").html('');  
            break;
           }
});
//function to populate child select box
function list(array_list)
{
    $("#child_selection").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $("#child_selection").append("<option value=""+array_list[i].value+"">"+array_list[i].display+"</option>");
    });
}

HTML

And if you are wondering where’s select box, here’s sample HTML for parent and child select box.

1
2
3
4
5
6
7
8
Category : <select name="parent_selection" id="parent_selection">
    <option value="">-- Please Select --</option>
    <option value="chocolates">Chocolates</option>
    <option value="vegetables">Vegetables</option>
    <option value="icecreams">Ice cream</option>
</select>
<select name="child_selection" id="child_selection">
</select>

Wrap Up

Here’s the complete example code. Just copy and save code below as HTML file and navigate to the file using your browser. You will find demo at the bottom of this page. Good luck!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">  
$(document).ready(function(){

//let's create arrays
var chocolates = [
    {display: "Dark chocolate", value: "dark-chocolate" },
    {display: "Milk chocolate", value: "milk-chocolate" },
    {display: "White chocolate", value: "white-chocolate" },
    {display: "Gianduja chocolate", value: "gianduja-chocolate" }];
   
var vegetables = [
    {display: "Broccoli", value: "broccoli" },
    {display: "Cabbage", value: "cabbage" },
    {display: "Carrot", value: "carrot" },
    {display: "Cauliflower", value: "cauliflower" }];
   
var icecreams = [
    {display: "Frozen yogurt", value: "frozen-yogurt" },
    {display: "Booza", value: "booza" },
    {display: "Frozen yogurt", value: "frozen-yogurt" },
    {display: "Ice milk", value: "ice-milk" }];

//If parent option is changed
$("#parent_selection").change(function() {
        var parent = $(this).val(); //get option value from parent
       
        switch(parent){ //using switch compare selected option and populate child
              case 'chocolates':
                list(chocolates);
                break;
              case 'vegetables':
                list(vegetables);
                break;             
              case 'icecreams':
                list(icecreams);
                break; 
            default: //default child option is blank
                $("#child_selection").html('');  
                break;
           }
});

//function to populate child select box
function list(array_list)
{
    $("#child_selection").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $("#child_selection").append("<option value=""+array_list[i].value+"">"+array_list[i].display+"</option>");
    });
}

});
</script>

</head>
<body> 
<div class="wrapper">
Category : <select name="parent_selection" id="parent_selection">
    <option value="">-- Please Select --</option>
    <option value="chocolates">Chocolates</option>
    <option value="vegetables">Vegetables</option>
    <option value="icecreams">Ice cream</option>
</select>
<select name="child_selection" id="child_selection">
</select>
</div>
</body>
</html>

Demo

Category :

45 Comments Add Comment

  • Great and very helpful stuff !

    Thank U.

     Reply
  • I have been learning from your tutorials, i also recently publish a similar tutorial, i hope you will also like my way of writing code. :)

    https://www.allphptricks.com/dynamic-dependent-select-box-using-jquery-and-ajax/

     Reply
  • Hi,

    if I put the all select part into a form, and hit submit, the page is reload and the selected data dispaeared. What should I add to leave the selected (parent and child, or parent and the choice for child) values still remain in the fields?

    Thank you in advance,
    Marta

     Reply
  • any thoughts as to why when I submit, the field is blank ?

     Reply
  • OK. found the problem. In the list(array_list) function, replace [“”] with [” ] in the third line. Note: I put brackets around the character pairs you need to swap, just to make it clear that the second pair of characters has a space. Don’t put them in the code! This fixes the JavaScript error and makes the code behave as intended.

     Reply
  • Oops. Typos.
    “The first element is ” means “The first select> element is ”
    “Clicking an in the first” means “Clicking an option the first select”

     Reply
  • HI!
    I’m trying to add another sub menu after the child_selection, anyone have an idea on how to accomplish this?

     Reply
  • Thanks a lot, never so simple like this before!

     Reply
  • Hello,
    Can you please help me.
    What if parent_selection is selected with a value ? How to make childs populated with the corresponding values ?
    Example Parent_selection is chocolate.
    Thank You

     Reply
  • Hey, AMAZING CODE !!
    No MySQL !!!! Perfect !!
    Thanks !!!
    Save my project (performance, time etc etc )

     Reply
  • Im doing something wrong im just not seeing it. Havent worked on pages in ages. tried full and individual script.
    saved parent_selection.js
    saved child_selection.js
    HTML.js
    and child_selection.htm
    Any advice? Please

     Reply
  • Saran your example is very nice, it’s ok from Google Chrome but no Internet Explorer. The IE debug browser send:
    La pagina adjunta está orientada al modo documento 7. Es posible que algunas características y API de consola no estén disponibles.
    Could you help me, please.

     Reply
  • Saran your example is very nice, i also did it but using database table, hope you like it and also help others.
    https://htmlcssphptutorial.wordpress.com/2015/08/25/dynamic-dependent-select-box-using-jquery-and-ajax/

     Reply
  • Tried it on http://chooseavirb.com/ptpros/ but no dice. Site is built on WordPress, with no jQuery conflicts based on the Firebug’s Inspector. My code is here: http://pastebin.com/pgK89W1f.

     Reply
  • Hi, thank you. Exactly what I was looking for. Even manage to get the localStorage implementation going with it – NICE.

     Reply
  • Hello and thank you so much for this article.

    Do you maybe know a solution to assign the selected values to a php variable?
    The aim would be to go to “../chocolate/dark-chocolate” and so on

    Thank you

     Reply
  • Hi
    I want this in single drop down list.
    Is it possible to do ?
    For Ex:
    1
    1 <!– I knw there is no Tag..this is just to explanin>
    2
    2

    Thanks in advance

     Reply
  • This code is not working for multiselect dropdown field.

     Reply
  • Thankyou so much..great post
    i want to use If-else instead of switches to compare selected options and populated child.. Any body help plzz??

     Reply
  • Well, can you make an example using database? Because I need to use a lot of select options which is editable in the back end. Awesome tutorials! Thank u!

     Reply
  • how to add 3 dynamic select box

     Reply
  • Hi, nice code but I wounder if it possible to add a button that will send a user to different pages depending on the chosen values?

     Reply
  • Any way to add a comment box dependent on what the user selects? Example:

    Please Select
    Dog
    Cat
    Turtle
    Other

    If a user selects other, a text box appears? I tried to do this through the case-switch but was unable.

     Reply
    • May be this?

      1
      2
      3
      4
      5
      6
      <select>
          <option >Dog</option>
          <option>Cat</option>
          <option>Other</option>
      </select>
      <div id="container"></div>

      jQuery :

      1
      2
      3
      4
      5
      6
      7
      $("select").change(function() {
          if($(this).find('option:selected').text()=="Other"){
              $("#container").html("<textarea></textarea>");
          }else{
              $("#container").html("");
          }
      });
    • That worked perfectly. I dont know why i didn’t think of that yesterday….gigantic brain fart. Thanks!

    • I also added some functionality to hide the other box. There is probably a better way to do this.

      in the arrays, added:

      1
      2
      var other = [
          {display: "other", value: "Null"}];

      in the .change(function(), added:

      1
      2
      3
      case 'other':
               list(other);
               break;

      jquery function:

      1
      2
      3
      4
      5
      $("select").change(function() {
          if($(this).find('option:selected').text()=="Other"){
              $("#child_sel").hide();
          }
          });

      didn’t need to update the contact page since all values are asigned on the jquery page.

  • Thank you for this article. it was very helpful!

    I need to adapt it for my form and send information captured to a database; I have tried to edit the parent_selection and child_selection to a corresponding name in my database, but the selection stops working.
    I need some help!
    Kind regards,
    Kay

     Reply
  • Jonathan-David Schröder

    Hello,
    Thank you very much for that nice article !
    here is a slightly simpler JS code that lends itself more easily to JS generation.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    $(document).ready(function () {

        //let's create arrays
        var options = {
            'chocolates': [{
                display: "Dark chocolate",
                value: "dark-chocolate"
            }, {
                display: "Milk chocolate",
                value: "milk-chocolate"
            }, {
                display: "White chocolate",
                value: "white-chocolate"
            }, {
                display: "Gianduja chocolate",
                value: "gianduja-chocolate"
            }],
                'vegetables': [{
                display: "Broccoli",
                value: "broccoli"
            }, {
                display: "Cabbage",
                value: "cabbage"
            }, {
                display: "Carrot",
                value: "carrot"
            }, {
                display: "Cauliflower",
                value: "cauliflower"
            }],
                'icecreams': [{
                display: "Frozen yogurt",
                value: "frozen-yogurt"
            }, {
                display: "Booza",
                value: "booza"
            }, {
                display: "Frozen yogurt",
                value: "frozen-yogurt"
            }, {
                display: "Ice milk",
                value: "ice-milk"
            }]
        };

        //If parent option is changed
        $("#parent_selection").change(function () {
            var parent = $(this).val(); //get option value from parent

            if (options[parent] == undefined) {
                return $("#child_selection").html('');
            }
            list(options[parent]);
        });

        //function to populate child select box
        function list(array_list) {
            $("#child_selection").html(""); //reset child options
            $(array_list).each(function (i) { //populate child options
                $("#child_selection").append("<option value="" + array_list[i].value + "">" + array_list[i].display + "</option>");
            });
        }

    });

    Thanks again !!

     Reply
    • Hi aweosme job, but how I can parse this code from file?

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      {
              'chocolates': [{
                  display: "Dark chocolate",
                  value: "dark-chocolate"
              }, {
                  display: "Milk chocolate",
                  value: "milk-chocolate"
              }, {
                  display: "White chocolate",
                  value: "white-chocolate"
              }, {
                  display: "Gianduja chocolate",
                  value: "gianduja-chocolate"
              }],
                  'vegetables': [{
                  display: "Broccoli",
                  value: "broccoli"
              }, {
                  display: "Cabbage",
                  value: "cabbage"
              }, {
                  display: "Carrot",
                  value: "carrot"
              }, {
                  display: "Cauliflower",
                  value: "cauliflower"
              }],
                  'icecreams': [{
                  display: "Frozen yogurt",
                  value: "frozen-yogurt"
              }, {
                  display: "Booza",
                  value: "booza"
              }, {
                  display: "Frozen yogurt",
                  value: "frozen-yogurt"
              }, {
                  display: "Ice milk",
                  value: "ice-milk"
              }]
          }
  • I Know that we can create a something like a troubleshoot application using this metod. but do you have any other idea how can i do a troubleshoot application with multiple selections.??

    Thanks… and this is a great article.

     Reply
    • 1
      2
      3
      4
      5
      6
      7
      8
      9
        $("#parent_selection").change(function () {
          $("#child_selection").html("<option>--- Selecteer Campagne(s)---</option>"); //reset child options
          $('select > option:selected').each(function(){
              var parent = $(this).val(); //get option value from parent
              if (options[parent] == undefined) {
                  return $("#child_selection").html('<option>--- Selecteer Campagne(s)---</option>');
              }
              list(options[parent]);
          });
  • This is a really great example that you have set out in such a way that makes it easy to understand and customise to my own site.
    Many thanks!

     Reply
  • A ton thanks for the reply.God bless!

     Reply
  • can u tell me the mysql code to obtain the value of the selected term so that i can use php and mysql to input data into database after the select.Kindly reply ASAP.

     Reply
  • I want to do the same thing for three drop downs….Can you please help me???

     Reply
  • Excellent

    Much of the examples use a Database calls for a lite dependent selection box this example serves the purpose.

    This source code rock – keep it up , appreciate you personally.

     Reply
  • Opss… sorry, forgot to insert the command into the php

    1
    2
    3
    4
    5
    Hi,

    Thanks for the article. Helpful for me. But I have a question:

    I used the following to get the selected option: <code lang="php"><?php if($_POST['name_of_select'] == 'Name of Option') {?> selected="selected"<? Php}?>

    By switching to the dynamic selection with jquery, the form sent is with the option selected in blank.

    Any idea how to retrieve the selected option on form submission?

    Thank you.

     Reply
  • Hi,

    Thanks for the article. Helpful for me. But I have a question:

    I used the following to get the selected option: selected=”selected”

    By switching to the dynamic selection with jquery, the form sent is with the option selected in blank.

    Any idea how to retrieve the selected option on form submission?

    Thank you.

     Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.