views:

24

answers:

3

Hi, I have an input field '#q' where a user can type a search query and returns a set of list items whose classes match it.

function queryData() {
   q = $('#q').val();
   q = q.toLowerCase();
   var qs = q.split(' ');
   $('.item').fadeOut(300);
   for (n in qs)        {
   $("li[class*='" + qs[n] + "']").fadeIn(1000);
                }
} 
<li class="apple"></li> <li class="apple banana"></li> <li class="banana"></li>

I'm not an expert so the code above may appear crude. So far, the code above is only able to display li's whose classes match the query regardless of the number of words in the query. So, if I type in "apple banana", any li with apple or banana as class will fadeIn(). How do I edit this function so that only the li's with BOTH apple and banana in its class will fadeIn()?

A: 

http://stackoverflow.com/questions/1041344/jquery-multiple-class-selector

Try this too:

function queryData() {
    $('.item').fadeOut(300);
    $("li."+
     (
      $('#q')
      .val()
      .toLowerCase()
      .split(/\s+/)
      .join('.')
     )
    ).fadeIn(1000);
}

Michael MacDonald
A: 

I'd use the list of terms to build a single query, eg

var qs = q.split(' ');
for (n in qs) {
    qs[n] = 'li.' + qs[n];
}
$(qs.join(', ')).fadeIn(1000);

This will fade in any "li" with any class entered.

The jquery-multiple-class-selector referenced only matches elements containing all classes

EDIT: Just saw your edit (require all classes). In that case, try

$('li.' + q.replace(' ', '.')).fadeIn(1000);
Phil Brown