javascript: dynamic drop down menu values

html, javascript

Solution

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>

Problem

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.

Original source