jQuery: onchange Event on Select with show/hide div

ยท

1 min read

If you have a dropdown list and you want to show a related text, you can do with .change() function.

HTML mocup

<select name="compare" id="compare">
    <option value="801" selected="selected">Item 1</option>
    <option value="803">Item 2</option>
    <option value="804">Item 3</option>
</select>

<div class="default">Item 1 TEXT</div>
<div class="info col_801">Item 1 TEXT</div>
<div class="info col_803">Item 1 TEXT</div>

CSS

#compare div.info {
    display:none;
}
#compare div.default {
    display:block;
}

jQuery Snippet

(function ($) {
    $(document).ready(function(){
        $('#compare').change(function(){
            var inputValue = $(this).val(); //Look for value
            var showCol = ".col_" + inputValue;
            //alert(showCol);            
            if (showCol) {
                $('.default').hide();
                $('.info').hide();
                $(showCol).show();
            }

        });
    });
})(jQuery);
ย