views:

149

answers:

1

I am trying to dynamically filter search results. Every result has tags associated with it that are used as classes.

<div class="search_results">
    <div class="html php jquery">
     I can do HTML, PHP and JQuery.
    </div>

    <div class="jquery asp pascal">
     I can do jQuery, ASP, and Pascal.
    </div>

    <div class="php basic webOS">
     I am a PHP, Visual Basic, and WebOS expert.
    </div>
</div>

I want to dynamically select results based on tag. I understand how to do this statically:

/* Hide all search results */
jQuery(".search_results div").hide(); 

/* Show everything with .php and .jquery tags */
jQuery(".search_results .php, .search_results .jquery").show()

However, I need this to happen dynamically based upon a list of checked boxes.

<div class="filters">
    <input type="checkbox" value="php" />
    <input type="checkbox" value="jquery" />
    <input type="checkbox" value="webOS" />
    etc..
</div>

When those boxes are checked, I want to filter my results.

My Question: What function would I use to do this? Every page result has different collection of tags. Would it be something like this?

// Create new array
var filter_array = new Array();

// wait for a filter checkbox to be clicked
jQuery(".filters input").click(function() {

    // Cycle through all input fields, and focus only on checked ones
    jQuery('.filters input:checked').each( function() {

     // Add current value to array
     filter_array.push(jQuery(this).val());

    });

    // Now filter the results
    for(i=0; i< filter_array.length;i++) {

     // Hide all results
     jQuery(".search_results div").hide(); /* Hide all search results */

     // What do I do here to make sure elements that are dipslayed meet all the filter criteria?

    }

});

Also, do I have to use the loop function? Is there a way to do this faster? Suppose I could have as many as 50-100 result elements on one page. I am not very familiar with jQuery optimization, so I am trying to find the most efficient way of doing this.

Thanks.

+4  A: 

You could do something like this:

jQuery('.filters input:checked').each( function() {

    // Add current value to array
    filter_array.push(jQuery(this).val());

});

jQuery(".search_results div").hide().filter('.' + filter_array.join(',.')).show();

This constructs a string like .jquery,.php,.python and then shows the divs matching that all-in-one selector. (Note that we've already limited the selection to .search_results div so we don't need to traverse the document more than once looking for those.)

VoteyDisciple