Filtering jQuery results using CSS tag

I am trying to dynamically execute filter search results. Each result has tags associated with it, which 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 a tag. I understand how to do it 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 on the 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 these boxes are checked, I want to filter the results.

My question is, what function would I use for this? Each page result has a 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 need to use a loop function? Is there a way to make it faster? Let's say there can be only 50-100 result items on one page. I am not very good at jQuery optimization, so I am trying to find the most efficient way to do it.

Thank.

+2


source to share


1 answer


You can 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 creates a string of type .jquery,.php,.python

and then shows a div

match against the all-in-one selector. (Note that we've already limited the selection .search_results div

, so we don't have to go through this document multiple times looking for them.)

+5


source







All Articles