Mark Roberts Mark Roberts - 10 months ago 46
Javascript Question

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

I have the following jQuery:

$(document).ready(function () {
$("#select_search").change(function () {
$('#' + $(this).val()).toggle();
<select id="select_search">
<option value="1">
<option value="2">
<option value="3">
<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.


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 () {
        $('#' + $(this).val()).show();

Demo: Fiddle