Complex filter in jquery

I have a list of products that I'm showing, and I'm currently working on a filtering function that does not use ajax.

Each product has a number of classes associated with it, based on the category in which it is located. 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 into one 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 that still works, which allows me to filter based on one 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 click function:

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

I know this is not an ideal way to do this, but I'm just looking for a little guidance.

I try to achieve two things after this:

When you click "AGAIN", remove this filter from the function. When you click another option, add it to the filter

, .., jquery , .

+3
2

- , , . , , . , "booo, ", .

var options = { 'cat1':false,'cat2':true,'cat3':false,'cat4':false,'cat5':false} //you can figure this out on your own.
function GetFilterValues(){
  var returnFilter = '';
  for(key in options) {
    if (options[key]) { //this checks to see if the value is true
      returnFilter = returnFilter + '.f_' + key + ' ,';
    }
  }
  //remove the last comma
  if (returnFilter.substring(returnFilter.length - 1) == ',') returnFilter = returnFilter.substring( 0, returnFilter.length - 1 );
  return returnFilter;
}

, :

function filterProd(filter){
  $(".f_all").hide(); // first hide all products
  $(GetFilterValues()).show();  // show only selected categories.
}

, :

function toggleOptionsValue(key){
  options[key] = !options[key];
}
+1

All Articles