Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: dynamic drop down menu values

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.

like image 299
fredriklind Avatar asked Dec 10 '13 00:12

fredriklind


People also ask

How do you dynamically populate a drop down list?

To add a dropdown list dynamically, you would need to create the HTML <select> element, its label and optionally a <br> tag. In pure JavaScript, you can use the document. createElement() method to programmatically create a dropdown list. Then you can call the Node's appendChild() method or jQuery's .

How do you populate values in one HTML dropdown list with another using simple JavaScript?

Learn how to add JavaScript to an HTML Page getElementById('firstList'); list1. options[0] = new Option('--Select--', ''); list1. options[1] = new Option('Snacks', 'Snacks'); list1. options[2] = new Option('Drinks', 'Drinks'); });


2 Answers

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>
like image 121
Tolgahan Albayrak Avatar answered Sep 25 '22 19:09

Tolgahan Albayrak


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>
like image 22
416E64726577 Avatar answered Sep 25 '22 19:09

416E64726577