mardi 26 juillet 2016

jquery combine filters instead of or

I have some jquery code for filtering with checkboxes which works fine, it loops through all the info I have and displays the correct filtered items, but I need it to combine the filters, at the moment it 'Or's through them. This is the jquery:

  var $filterCheckboxes = $('input[type="checkbox"]');

  function init(){
    $filterCheckboxes.on('change', function() {

var selectedFilters = {};

$filterCheckboxes.filter(':checked').each(function() {

  if (!selectedFilters.hasOwnProperty(this.name)) {
    selectedFilters[this.name] = [];
  }

  selectedFilters[this.name].push(this.value);

});

var $filteredResults = $('.card');

// loop over the selected filter name -> (array) values pairs
$.each(selectedFilters, function(name, filterValues) {

  // filter each .card element
  $filteredResults = $filteredResults.filter(function() {

    var matched = false,
      currentFilterValues = $(this).data('category').split(' ');

    // loop over each category value in the current .card's data-category
    $.each(currentFilterValues, function(_, currentFilterValue) {

      // if the current category exists in the selected filters array
      // set matched to true, and stop looping. as we're ORing in each
      // set of filters, we only need to match once

      if ($.inArray(currentFilterValue, filterValues) != -1) {
        matched = true;
        return false;
      }
    });

    // if matched is true the current .card element is returned
    return matched;

  });
});

$('.card').hide().filter($filteredResults).show();

});

}

init();




Aucun commentaire:

Enregistrer un commentaire