10

i want to create two drop down form and if i select an item on the first menu the second menu will display corresponding value. for example: if i select "fruit" on the first menu, then the second menu will display "apple", "banana" and so on. it must have values on them so i can insert it into database.

html is as follows:

<select id="firstmenu" name="fruit">
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<br/>
<select id="secondmenu" name="vegetable">
<option value="carrot">carrot</option>
<option value="celery">celery</option>
</select>

javascript; i was thinking using something like this but i lack understanding of javascript

<script>
var a=document.forms["myform"]["fruit"].value;
var b=document.forms["myform"]["vegetable"].value;

if (a=="fruit")
{
...
}
</script>

could someone give me a code example? help is much appreciated, thanks.

4 Answers 4

8

Well,

how about using jQuery?

var items = [{
    name: '---',
    value: '',
    subitems: []
  },
  {
    name: 'Fruit',
    value: 'fruit',
    subitems: [{
        name: 'Apple',
        value: 'apple'
      },
      {
        name: 'Banana',
        value: 'banana'
      }
    ]
  },
  {
    name: 'Vegetable',
    value: 'vegetable',
    subitems: [{
        name: 'Carrot',
        value: 'carrot'
      },
      {
        name: 'Celery',
        value: 'celery'
      }
    ]
  }
];


$(function() {
  var temp = {};

  $.each(items, function() {
    $("<option />")
      .attr("value", this.value)
      .html(this.name)
      .appendTo("#firstmenu");
    temp[this.value] = this.subitems;
  });

  $("#firstmenu").change(function() {
    var value = $(this).val();
    var menu = $("#secondmenu");

    menu.empty();
    $.each(temp[value], function() {
      $("<option />")
        .attr("value", this.value)
        .html(this.name)
        .appendTo(menu);
    });
  }).change();


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<select id="firstmenu" name="fruit"></select>
<br/>
<select id="secondmenu" name="vegetable"></select>

1
  • 6
    page doesn't exist.
    – Max
    Commented Feb 28, 2019 at 13:08
5

I used Javascript to create a dropdown menu. Then, if the user chose fruit in the main dropdown menu, I created "fruit" options, and if the user chose vegetables in the main dropdown menu, I created "vegetable" options.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function displayAccordingly() {

            //Call mainMenu the main dropdown menu
            var mainMenu = document.getElementById('mainMenu');

            //Create the new dropdown menu
            var whereToPut = document.getElementById('myDiv');
            var newDropdown = document.createElement('select');
            newDropdown.setAttribute('id',"newDropdownMenu");
            whereToPut.appendChild(newDropdown);

            if (mainMenu.value == "fruit") { //The person chose fruit

                //Add an option called "Apple"
                var optionApple=document.createElement("option");
                optionApple.text="Apple";
                newDropdown.add(optionApple,newDropdown.options[null]);

                //Add an option called "Banana"
                var optionBanana=document.createElement("option");
                optionBanana.text="Banana";
                newDropdown.add(optionBanana,newDropdown.options[null]);

            } else if (mainMenu.value == "vegetable") { //The person chose vegetabes

                //Add an option called "Spinach"
                var optionSpinach=document.createElement("option");
                optionSpinach.text="Spinach";
                newDropdown.add(optionSpinach,newDropdown.options[null]);

                //Add an option called "Zucchini"
                var optionZucchini=document.createElement("option");
                optionZucchini.text="Zucchini";
                newDropdown.add(optionZucchini,newDropdown.options[null]);

            }

        }
    </script>
</head>
    <body>
        <select id="mainMenu" onchange="displayAccordingly()">
        <option value="">--</option>
        <option value="fruit">Fruit</option>
        <option value="vegetable">Vegetable</option>
        </select>
        <div id="myDiv"></div>
    </body>

</html>

Every time the value of the dropdown menu changes, the function displayAccordingly() runs. It creates a new dropdown menu, and then, if the value of the main dropdown menu is fruit, it adds fruit options to the newly-created dropdown menu, and if the value of the main dropdown menu is vegetables, then it adds vegetable options to the newly-created dropdown menu.

I hope this helps! :)

EDIT: If you change the value of the dropdown twice, it creates 2 dropdown menus. I added another variable to fix that:

<!DOCTYPE html>
<html>
    <head>
    <script type="text/javascript">
    var created = 0;

        function displayAccordingly() {

            if (created == 1) {
                removeDrop();
            }

            //Call mainMenu the main dropdown menu
            var mainMenu = document.getElementById('mainMenu');

            //Create the new dropdown menu
            var whereToPut = document.getElementById('myDiv');
            var newDropdown = document.createElement('select');
            newDropdown.setAttribute('id',"newDropdownMenu");
            whereToPut.appendChild(newDropdown);

            if (mainMenu.value == "fruit") { //The person chose fruit

                //Add an option called "Apple"
                var optionApple=document.createElement("option");
                optionApple.text="Apple";
                newDropdown.add(optionApple,newDropdown.options[null]);

                //Add an option called "Banana"
                var optionBanana=document.createElement("option");
                optionBanana.text="Banana";
                newDropdown.add(optionBanana,newDropdown.options[null]);

            } else if (mainMenu.value == "vegetable") { //The person chose vegetabes

                //Add an option called "Spinach"
                var optionSpinach=document.createElement("option");
                optionSpinach.text="Spinach";
                newDropdown.add(optionSpinach,newDropdown.options[null]);

                //Add an option called "Zucchini"
                var optionZucchini=document.createElement("option");
                optionZucchini.text="Zucchini";
                newDropdown.add(optionZucchini,newDropdown.options[null]);

            }

            created = 1

        }

        function removeDrop() {
            var d = document.getElementById('myDiv');

            var oldmenu = document.getElementById('newDropdownMenu');

            d.removeChild(oldmenu);
        }
    </script>
    </head>
    <body>
        <select id="mainMenu" onchange="displayAccordingly()">
        <option value="">--</option>
        <option value="fruit">Fruit</option>
        <option value="vegetable">Vegetable</option>
        </select>
        <div id="myDiv"></div>
    </body>

</html>
1
  • Note: I realized that if you change the value of the main dropdown, you get a new dropdown with the corresponding values. But, if you change the value of the main dropdown again, yet another dropdown appears. To fix that, I added a created variable, and at the beginning of displayAccordingly(), if there is already another dropdown menu on the page, it deletes it. Commented Dec 10, 2013 at 2:43
2

I guess this example may suits you requirement .Here I have set some static content for second option in dynamicdropdown() function.No problem you can make that with your dynamic content by Option object.For example

document.getElementById("subcategory").options[i] = new Option("key","value",false, false)

i will be you number of for dynamic values.

Please refer the demo part DEMO of dynamic drop down menu values

<html>
    <head>
        <title>Create dyanamic dropdown list in javascript</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script language="javascript" type="text/javascript">
        function dynamicdropdown(listindex)
        {
            document.getElementById("subcategory").length = 0;
            switch (listindex)
            {
            case "fruits" :
                document.getElementById("subcategory").options[0]=new Option("Please select fruits","");
                document.getElementById("subcategory").options[1]=new Option("apple","apple");
                document.getElementById("subcategory").options[2]=new Option("banana","banana");
                document.getElementById("subcategory").options[3]=new Option("mangoes","mangoes");
                break;

            case "meats" :
                document.getElementById("subcategory").options[0]=new Option("Please select meats","");
                document.getElementById("subcategory").options[1]=new Option("pigs","pigs");
                document.getElementById("subcategory").options[2]=new Option("chicken","chicken");
                break;
            }
            return true;
        }
       </script>
    </head>
    <title>Dynamic Drop Down List</title>
    <body>
        <div class="category_div" id="category_div">Please specify food items:
        <select name="category" class="required-entry" id="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
            <option value="">Select food items</option>
            <option value="Php">fruits</option>
            <option value="Javascript">meats</option>
        </select>
        </div>
        <div class="sub_category_div" id="sub_category_div">Please select foods:
        <script type="text/javascript" language="JavaScript">
            document.write('<select name="subcategory" id="subcategory"><option value="">Please select foods</option></select>')
        </script>
        <noscript>
            <select name="subcategory" id="subcategory" >
            <option value="">Please select foods</option>
            </select>
        </noscript>
        </div>
    </body>
</html>

Also refer for more details: Reference

1

i am a little confused about your problem, but i just wrote two sample examples for you DEMO1 and DEMO2

DEMO1 - javascript

window.onload = function() {
    document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'firstmenu','secondmenu');}, false);
};

function ha(e,first,second){
    var firstOptions = document.getElementById(first).options;
    var secondOptions = document.getElementById(second).options;
    for(var i = 1, j = firstOptions.length; i < j; i++) {
        secondOptions[i].value = firstOptions[i].value;
        secondOptions[i].text = firstOptions[i].text;
    }
};

DEMO2 - javascript

window.onload = function() {
   document.getElementById("firstmenu").addEventListener('change',function(e) {ha(e,'secondmenu');}, false);
   document.getElementById("secondmenu").addEventListener('change',function(e) {ha(e,'firstmenu');}, false);
};
function ha (e,id){
   var index = e.target.selectedIndex;
   document.getElementById(id).selectedIndex = index;
};

DEMO1 and DEMO2 have same HTML :

<select id="firstmenu" name="City">
    <option value="--">--</option>
    <option value="NY">NY</option>
    <option value="LA">LA</option>
</select>
<br/>
<select id="secondmenu" name="zipCode">
    <option value="--">--</option>
    <option value="10001">10001(NY)</option>
    <option value="90001">90001(LA)</option>
</select>

Hope this will help you !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.