jQuery - hide & show li items that have a variable class
Solution 1
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();
});
});
Solution 2
You do not need double quotes
in not()
selector as they will cause the variable to be treated as string
.
$("#mapContent ul li").not('.' + chosenCat).addClass("displayNone");
The code you have will pass '.' +chosenCat
in the not selector instead of passing .opt0
or .opt1
etc depending upon selection.
Also you probably need to do it on change event of the select, also if you just want to show and hide the you can use the show and hide function.
$('select[name="mapCat"]').change(function(){
var chosenCat = $(this).val();
$("#mapContent ul li").show()
$("#mapContent ul li").not('.' + chosenCat).hide();
});
colleen
Updated on July 16, 2022Comments
-
colleen almost 2 years
I have a drop-down menu as an unordered list. When a category is selected, I only want the
li
with the same class as the value of the selection to remain visible.I have tried using the
not
selector but I'm having trouble using it in combination with a variable class - that is also the same as the value of the selection.$(document).ready(function(){ var chosenCat = $('select[name="mapCat"]').val(); var className = $('#mapContent ul li.'); $("#mapContent ul li").not("'.' +chosenCat").addClass("displayNone"); });
I've been making edits but this jQuery snippet isn't working. How do I correctly write the variable I want to remain visible? Or is the error in the
val()
I'm pulling?the 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; }
-
colleen about 10 yearsgreat advice. thanks for the demo. obviously, I'm new to query - I need to familiarize myself with more function options.