Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complex filter in jquery

Tags:

jquery

php

filter

I have a list of products I am displaying and I am currently working on a filtering function that does not use ajax.

Every product has a series of classes attached to it based on a category it falls under. So like this:

<li class="f_all f_cat1 f_cat2">Product 1</li>
<li class="f_all f_cat1 f_cat3 f_cat_4">Product 2</li>
<li class="f_all f_cat4 f_cat5 f_cat6">Product 3</li>

This means that many products fall under the same category.

These are the filter options:

<table cellspacing="10">
  <tr>
    <td class="item" id="p_1">Category 1</td>
    <td class="item" id="p_2">Category 2</td>
    <td class="item" id="p_3">Category 3</td>
  </tr>
</table>

I have a basic filter working so far, that allows me to filter based on a single category, that looks like this:

function filterProd(filter){
$(".f_all").hide(); // first hide all products
$(".f_"+filter).show();  // show products only for this category
}

Then the click function:

$("#p_1").click(function(){filterProd("cat1");});
$("#p_2").click(function(){filterProd("cat2");});
$("#p_3").click(function(){filterProd("cat3");});

I know that this is not the ideal way to do this but i'm just looking for a little guidance.

I am trying to achieve 2 things after this:

  • When the option is clicked AGAIN, remove that filter from the function
  • When another option is clicked, ADD it to the filter
  • I am assuming a function of sorts that accepts an array of values etc, but i'm fairly new to jquery and would appreciate any help i can get at this point.

    like image 909
    dangermark Avatar asked Aug 10 '26 04:08

    dangermark


    1 Answers

    One option would be to store the filters in an array: http://jsfiddle.net/4yWWH/

    EDIT: modified to show all products and exit if there are no filters: http://jsfiddle.net/4yWWH/1/

    like image 52
    Jonathan Avatar answered Aug 11 '26 17:08

    Jonathan