Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

nicholas maddren
nicholas maddren
12,793 Points

jQuery - When selected show other select element

Hey guys I'm having a hard time finding a way to make another select element appear when the user has selected the first select element.

As it stands my select element contains a number of car manufacturers, the default select caption is "Select Manufacturer", when the user has selected a manufacturer I want the "Models" select to appear. I can't have the user selecting the default select caption and then having the Models select box show as there would be no models as a manufacturer hasn't been selected.

Any idea how I can do this?

3 Answers

Sander de Wijs
PLUS
Sander de Wijs
Courses Plus Student 22,267 Points

You could place at all the options as an array, with the first value [0] being 'Select manufacturer'. After that you can use jQuery to only show the models select if the array index is [1] or higher.

Or use the val() method to determine if the value of an option is equal to 'Select manufacturer' and keep the models selectbox hidden if it is.

Chris Malcolm
Chris Malcolm
2,909 Points

Hi Nicholas try this (see comments on codepen): http://codepen.io/anon/pen/ALvbc

Shaker Advertising
Shaker Advertising
5,395 Points

A simple way to do this is check if a certain option in your first select is selected and then hide or show the second select box with conditional logic.

Your Html

<select name="manufacturer" id="manufacturer"> 
    <option value="" class="default" selected>(select)</option>
    <option value="Manufacturer One">Manufacturer One</option>
    <option value="Manufacturer Two">Manufacturer Two</option>
</select>

<select name="model" id="model"> 
    <option value="" selected>(select)</option>
    <option value="Model One">Model One</option>
    <option value="Model Two">Model Two</option>
</select>

Your jQuery

$(function(){
    $("#model").hide();  // By default use jQuery to hide the second modal

    // We can use the change(); function to watch the state of the select box and run some conditional logic every time it's changes to hide or show the second select box
    $("#manufacturer").change(function(){
        if( $(".default").is(:selected) ){
            $("#model").hide();
        } else {
            $("#model").show();
        }
    });
});