javascriptjqueryhtmldynamic-ui

How to make the value of one select box drive the options of a second select box


I want to make an HTML form with 2 select boxes. The selected option in the first select box should drive the options in the second select box. I would like to solve this dynamically on the client (using javascript or jQuery) rather than having to submit data to the server.

For example, let's say I have the following Menu Categories and Menu Items:

I would have two select boxes, named Menu Category and Items, respectively. When the user selects Sandwiches in the Menu Category box, the options in the Items box will only show Sandwich options.

To make this more challenging, let's assume that I don't know what the menu items or categories are until I'm ready to send the page to the client. I'll need some way to "link" the data for the two select lists, but I don't know how that would be done.

I'm stuck as how I might approach this. Once I filter out the 2nd list one time, how do I "find" the list options once I change my menu category in the 1st list? Also, if I'm thinking in SQL, I would have a key in the 1st box that would be used to link to the data in the 2nd box. However, I can't see where I have room for a "key" element in the 2nd box.

How could this problem be solved with a combination of jQuery or plain javascript?


Solution

  • Check out this example on Dynamic Drive, or you can search google for "chained select" for other examples.

    Edit: And here is a very nice Remy Sharp tutorial: Auto-populating Select Boxes using jQuery & AJAX


    Well, because I have OCD, I threw together a demo for you.

    It defines a variable could also loaded as json if required.

    HTML

    <select id="cat"></select> <select id="items" disabled></select>
    

    Script

    $(document).ready(function(){
    
    var menulist = { "categories" : [{
     "category" : "Sandwiches",
     "items" : [
       {"name": "Turkey"},
       {"name": "Ham"},
       {"name": "Bacon"}
      ]
     },{
     "category" : "Sides",
     "items" : [
       {"name": "Mac 'n Cheese"},
       {"name": "Mashed Potatoes"}
      ]
     },{
     "category" : "Drinks",
     "items" : [
       {"name": "Coca Cola"},
       {"name": "Sprite"},
       {"name": "Sweetwater 420"}
      ]
     }]
    };
    
    var i,c = '<option>Select a category</option>', opt = $('<option/>');
    var menu = menulist.categories;
    
    for (i=0; i < menu.length; i++){
     c += '<option>' + menu[i].category + '</options>';
    }
    $('#cat')
     .html(c)
     .change(function(){
      var indx = this.selectedIndex - 1;
      if (indx < 0) {
       $('#items').empty().attr('disabled','disabled');
       return;
      }
      var item = '<option>Select an item</option>';
      for (i=0; i < menu[indx].items.length; i++){
        item += '<option>' + menu[indx].items[i].name + '</options>';
      }
      $('#items').html(item).removeAttr('disabled');
     });
    
    });