Home / jQuery: Toggling select boxes when one changes

jQuery: Toggling select boxes when one changes

I was asked a couple of days ago on my get and set form values with jQuery post how to make a secondary select box appear with jQuery when the first one is changed. The first might contain a list of countries and the second one some cities which changes as the country changes, allowing the user to select both their country and city. This post shows how to do this with several hidden sub-selects, and an earlier post shows how to do it with JSON and AJAX.

Working example

Select which fruit you would like from the first drop down box and based on the value of that a second one will appear allowing you to select the variety.

Please note that if you are reading this in a feed reader the above example will not work so you’ll need to click through to view this post in a web browser.

How it works

There are 4 select boxes in total in the above example: the one you can see before selecting a fruit, and then one for each fruit with the varities.

The subselects have the class "exampleSubselect" and these are hidden initially with CSS. The jQuery hides them all based on this class selector and then one of them is made visible based on the value of the fruit select.

The full code for the above example is here:

Javascript:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
    $('#exampleFruit').change(function() {
        var val = $('#exampleFruit').val();
        $('.exampleSubselect').hide();
        if(val) {
            $('#example'+val).show();
        }
    });
});

</script>

CSS:

<style type="text/css">
.exampleSubselect {
    display: none;
}
</style>

HTML:

<select id="exampleFruit">
    <option value="">-- Please Select --</option>
    <option>Apple</option>
    <option>Banana</option>
    <option>Orange</option>
</select>
<select id="exampleApple" class="exampleSubselect">
    <option>Red Delicious</option>
    <option>Granny Smith</option>
    <option>Cox's Orange Pippin</option>
</select>
<select id="exampleBanana" class="exampleSubselect">
    <option>Plantain</option>
    <option>Burro</option>
    <option>Cavendish</option>
</select>
<select id="exampleOrange" class="exampleSubselect">
    <option>Blood</option>
    <option>Navel</option>
    <option>Valencia</option>
</select>

Conclusion

Having multiple select boxes makes it an easy to implement solution without having to mess around with data, which is great if the data isn’t coming from a database or similar.

However it becomes less useful when dealing with a lot of data, or data that may change over time. Also read my Load JSON data with jQuery, PHP and MySQL post which shows how to do the same sort of thing presented on this page but in a more dynamic way.