dimanche 21 juin 2015

jQuery/Javascript get classes of multiple elements to show an element with this class

I'm struggling with a jQuery live search.

First of all the live search update with the following code works.

  //live search function
  function live_search(list) {
    $("#search")
      .change( function () {
        //getting search value
        var searchtext = $(this).val();
        if(searchtext) {
          //finding If content matches with searck keyword
          $matches = $(list).find('a:Contains(' + searchtext + ')').parent();
          //hiding non matching lists
          $('li', list).not($matches).slideUp();
          //showing matching lists
          $matches.slideDown();

        } else {
          //if search keyword is empty then display all the lists
          $(list).find("li").slideDown(200);
        }
        return false;
      })
    .keyup( function () {
        $(this).change();
    });
  }

The problem is that my list is alphabetically and containt an header for each letter:

<ul class="begrippen_list leftList col-sm-12 col-md-6">
   <li class="header a">A</li>
   <li class="a">
      <a href="#">All</a>
   </li>
   <li class="a">
      <a href="#">Auto</a>
   </li>
   <li class="header b">B</li>
   <li class="b">
      <a href="#">Balls</a>
   </li>
   <li class="b">
      <a href="#">Bus</a>
   </li>
</ul>

Now to the problem: when I type au in the input, the jQuery only shows the list-item with "Auto", but I also want the header with the class a (class of li) to be shown. When I only type a the headers with the class "a" and class "b" have to be shown.

I think to check all $matches for their class and displaying the li.header with classes of the $matches could be the solution but couldn't get it work.

Cheers!

Aucun commentaire:

Enregistrer un commentaire