S
S
sergey2021-07-13 20:55:41
JavaScript
sergey, 2021-07-13 20:55:41

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;
}

An example of the state of Virginia is already empty and needs to be hidden
60edd3cd8e931358638485.png
https://jsfiddle.net/sergsagan/ofLj5uwa/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-13
@zorro76

$('#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 question

Ask a Question

731 491 924 answers to any question