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

Posted by Ben McCormack on Stack Overflow See other posts from Stack Overflow or by Ben McCormack
Published on 2010-04-08T21:19:37Z Indexed on 2010/04/08 21:23 UTC
Read the original article Hit count: 279

Filed under:
|
|
|

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:

  • Sandwiches
    • Turkey
    • Ham
    • Bacon
  • Sides
    • Mac 'n Cheese
    • Mashed Potatoes
  • Drinks
    • Coca Cola
    • Sprite
    • Sweetwater 420

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.

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?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript