Search code examples
jqueryhidden

How to hide empty parens when children are empty


I am trying to build a dynamic search box to filter items in a list - the list is setup as a series of unordered lists, each of which contains a number of items

When the user enters a letter into the search box then I only want to return the list items which contains that letter/letters - that part works fine

However, I have headings inside each unordered list so whilst all the items in the list are hidden the heading is not and I want to hide the heading/whole unordered list if none of its children are visible

Conversely, when the search box is changed the unordered list should show or hide as appropriate.

HTML

<input type="text" id="search-input" name="search-fields">  

<ul class="sorted-list">
<legend>Section 1</legend>
<li class="tmenu"><span class="tmenuspan">bob</span>
<li class="tmenu"><span class="tmenuspan">fred</span>
<li class="tmenu"><span class="tmenuspan">tom</span>
</ul>

<ul class="sorted-list">
<legend>Section 2</legend>
<li class="tmenu"><span class="tmenuspan">mike</span>
<li class="tmenu"><span class="tmenuspan">john</span>
<li class="tmenu"><span class="tmenuspan">david</span>
</ul>

JS

$("#search-input").on("keyup", function () {
    var search = this.value;

    if (search !== '') {

        $('.tmenuspan').each(function() {
            if ($(this).text().toLowerCase().indexOf(search) >= 0) {
                $(this).closest('.tmenu').show();
            } else {
                $(this).closest('.tmenu').hide();
            }
        });

        $('ul.sorted-list').each(function() {
            if($('ul.sorted-list > li').is(':hidden')) {
                //$(this).closest('ul.sorted-list').hide();
            }
        });
    } else {
        $('.tmenu').show();
        $('ul.card-tabs-sorted').show();
    }

});

In the above when I type bob, all the tmenu items are hidden except the one containing bob which is what I need but the section 2 heading/unordered list still shows - this is the bit I cannot figure out.

https://jsfiddle.net/9Lw675ep/


Solution

  • JS

    var $ul = $('.sorted-list');
    var $li = $ul.find('li');
    
    $("#search-input").on("keyup", function () {
      var inputValue = $.trim(this.value); // Trim values!
      var rgx = new RegExp(inputValue, "i"); // Case insensitive
    
      // LI
      $li.show().filter(function() {
        return ! rgx.test($(this).text())
      }).hide();
    
        // UL
      $ul.show().filter(function() {
        return ! $(this).find("li:visible").length;
      }).hide();
    });
    

    https://jsfiddle.net/n62k7hxL/