Javascript: Display a second drop-down menu or div based on user’s selection in first drop-down menu

Here is the Javascript that I use to display a second drop-down menu or a div based on a user’s selection in the first drop-down menu.

Add this to the section of your web page:

<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'></script>
<script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
    $('#color-options').hide();
     $('#<span style="color: #ff0000;">your-dropdown-menu-id</span>').change(function () {
        if ($('#<span style="color: #ff0000;">your-dropdown-menu-id</span> option:selected').text() == "<span style="color: #ff0000;">User's selection</span>"){
            $('#color-options').show();
        }
         else {
              $('#color-options').hide();
         }
    });
});
//]]>
</script>

First, change the text “your-dropdown-menu-id” in the code above to the ID of your first drop-down menu.

For example, if this is your drop down menu code:

<select name="select_size" id="select_size">
<option value="large">Large</option>
<option value="medium">Medium<option>
<option value="small">Small</option>
</select>

The ID in the Javascript should be changed to “select_size.”

Now, simply either wrap the second drop down menu in a div with the ID “color-options” or add the ID “color-options” to the second drop down menu itself.

For example, let’s say all of the T-shirts you are selling come in one color – black – unless the user is purchasing a size small, in which case they can choose the color blue if they prefer. Here is what the second drop down menu would look like:

<select name="select_color" id="color-options">
<option value="black">Black</option>
<option value="blue">Blue<option>
</select>

Or, you could wrap the drop down menu in a div with the ID of “color-options”.

You will now need to change “User’s selection” in the Javascript to the text of the drop down menu item that you want to add the event to, in this case it would be “Small.”

To see an example of this code in action, click here.

As you can probably see, there are many different things you can do with this code – such as display different images or different text based on the user’s selection in the first drop down menu. All you have to do is wrap the text or image that you want to be dependent on a user’s selection in the ID “color-options” or whatever you change the ID to.

Let me know if you have any questions!

Meet the author

Libby Fisher is an experienced freelance web developer, recently relocated from Seattle to Boston, and passionate about developing websites that are both aesthetically appealing and intuitively usable - or as she prefers: "beautifully effective."