Filtering a list as you type with jQuery

Viewed 51019

I was planning to create an unordered list of users of my web application using a simple database query, but then was planning to let people filter this list down by typing the person's name they're looking for into a text input.

I was hoping to use jQuery to match the string in the input box to any inside one of the list items, then hide the other ones, maybe by applying a new class dynamically to the ones that contain the matching string, and hiding all others that don't contain that class.

Does anyone know of a good way to do this?

6 Answers

Taking main inspiration from this W3 example, I developed a possible alternative and compact solution.

In the example linked is possible to see 3 different options:

  • Filter only UL items
  • Filter any item
  • Filter any item with css animated effect

The simplest JS code is the following, that simply filter any kind of element thanks to $("#anyItemList *") selector:

  $("#anyItemListInputFilter").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#anyItemList *").filter(function() {
        let item = $(this).text().toLowerCase().indexOf(value) > -1;
      $(this).toggle(item);
    });
  });

In case that desired filtering would be only for UL list, that selector could changed with $("#ulList li") (as in example)

If you want also to add css animation effect, there are some constraints:

  • Needed a pre-defined max-height in px (maybe not so much impacting if you set an enough taller one)
  • overflow-y:hidden;

So I was forced to declare:

#anyItemAnimatedList * {
  transition:all 0.5s ease;
  opacity:1;
  max-height:500px;
 overflow-y:hidden;
}

#anyItemAnimatedList ul {
  list-style-position:inside;
}

#anyItemAnimatedList .hidden {
  max-height:0;
  opacity:0;
  border:0;
}

Hiding effect is made with a combination of opacity and max-height css transitions, and border:0 is necessary to override button tag default browser style.

In addition, in case of OL and UL lists is necessary to set list-style-position:inside; due to a strange default behaviour shared by Firefox and Chrome that hide bullets in case of default list-style-position:outside.

For Firefox this is a known bug since 2003!!! but also Chrome has the same behaviour.

Related