Answer the question
In order to leave comments, you need to log in
How to hide an empty list category when filtering?
There is a list of states and cities, we filter the cities, according to the first letters entered, the screening letters are not suitable. It is
necessary to hide the state in which the cities are not selected
<ul id="city-list">
<li class="state">MARYLAND</li>
<li class="city">Aberdeen</li>
<li class="city">Danville</li>
<li class="city">Kensington</li>
<li class="city">Queenstown</li>
<li class="state">VIRGINIA</li>
<li class="city">Abingdon</li>
<li class="city">Dublin</li>
<li class="city">Linton Hall</li>
<li class="city">Marshall</li>
<li class="state">WASHINGTON</li>
<li class="city">Aberdeen</li>
<li class="city">Easton</li>
<li class="city">Lynnwood</li>
</ul>
$('#cityFilter').on('keyup', function () {
var value = this.value;
if (value != "") {
$('#city-list li').hide().each(function () {
if ($(this).not('.state').text().toLowerCase().search(value.toLowerCase()) > -1) {
$(this).prevAll('.state').first().add(this).show();
$('li.state').show();
}
});
} else {
$('#city-list li').show().each(function () {
$(this).prevAll('.state').first().add(this).show();
$('li.state').show();
});
}
});
.state {
font-weight: bold;
}
Answer the question
In order to leave comments, you need to log in
$('#cityFilter').on('input', function() {
const value = this.value.toLowerCase();
$('#city-list .city')
.hide()
.filter((i, n) => $(n).text().toLowerCase().includes(value))
.show();
$('#city-list .state')
.hide()
.filter((i, n) => $(n).nextUntil('.state').is(':visible'))
.show();
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question