JQuery - hide and show elements that have a variable class

I have a dropdown as an unordered list. When a category is selected, I want only liwith the same class as the highlight value, which will remain visible.

I tried to use a selector not, but I had problems using it in combination with a class of variables - this is also the same as the value of the choice.

$(document).ready(function(){
    var chosenCat = $('select[name="mapCat"]').val();
    var className = $('#mapContent ul li.');
    $("#mapContent ul li").not("'.' +chosenCat").addClass("displayNone");   
});

I am making changes, but this jQuery fragment does not work. How to write the variable that I want to remain visible? Or a mistake in val()I pull?

HTML:

<select name="mapCat">
    <option value="opt0" selected="selected">SELECT A CATEGORY</option>
    <option value="opt1">UNIVERSITIES</option>
    <option value="opt2">HOSPITALS</option>
</select>
<div id="mapContent">
    <ul>
       <li class="opt1">University X</li>
       <li class="opt2">Hospital X</li>
       <li class="opt2">Hospital Y</li>
       <li class="opt1">University Y</li>
       <li class="opt1">University Z</li>
       <li class="opt2">Hospital Z</li>
    </ul>
</div>

CSS snippet:

.displayNone {
   display: none;
 }
+3
source share
2 answers

try the following code

$( document ).ready(function() {        
         $('select[name="mapCat"]').change(function(){
            var chosenCat =$(this).val();       
            $('#mapContent ul li').hide();
            $('#mapContent ul li.'+chosenCat).show();
         });
        });
+2
source

quotes not(), string.

$("#mapContent ul li").not('.' + chosenCat).addClass("displayNone");   

, , '.' +chosenCat .opt0 .opt1 .. .

, , , , show and hide.

Live Demo

$('select[name="mapCat"]').change(function(){
     var chosenCat = $(this).val();  
     $("#mapContent ul li").show()
     $("#mapContent ul li").not('.' + chosenCat).hide();   
});
+2

All Articles