Mark Roberts Mark Roberts - 6 months ago 22
Javascript Question

Jquery hide/show div from select box is not working, I can't figure out why?

I have the following jQuery:

<script>
$(document).ready(function () {
$(".search_type").hide();
$("#select_search").change(function () {
$('#' + $(this).val()).toggle();
});
});
</script>
<select id="select_search">
<option value="1">
<option value="2">
<option value="3">
</select>
<div id="1" class="search_type">Some Text</div>
<div id="2" class="search_type">Some Text</div>
<div id="3"class="search_type">Some Text</div>
enter code here


Currently I have it display the corresponding div based on select box change, however, this does not remove it if the select box is changed again.

Is there an if(($this):not.val()).....Something something hide? Sorry, I'm new to JS / jQuery, and am really struggling here.

Answer

You need to hide the previously displayed element, one easy way to sue hide all the search_type elements again the the change handler then show current element

jQuery(function ($) {
    var $stypes = $(".search_type").hide();
    $("#select_search").change(function () {
        $stypes.hide();
        $('#' + $(this).val()).show();
    }).change();
});

Demo: Fiddle

Comments