Multiple checked search result filter using AJAX

In my traveling website I want to filter the search result using multiple check boxes. Currently my code is working as follows.

If I check "Near Airport", it will show only the hotels with the data tag "airport". But when I want to filter the hotels which are near to both the air port and the shopping district at the same time, it will not work. It shows the list of hotels which have the data tag "airport" OR "shopping". I want to change it to list the hotels which have both data tags "airport" AND "shopping".

Screenshot of the web site http://prntscr.com/c49csj

Code in Context

$(document).ready(function(){
    $('.category').on('change', function(){
      var category_list = [];
      $('#filters :input:checked').each(function(){
        var category = $(this).val();
        category_list.push(category);
      });

      if(category_list.length == 0)
        $('.resultblock').fadeIn();
      else {
        $('.resultblock').each(function(){
          var item = $(this).attr('data-tag');
          var itemarr = item.split(',');
          $this = $(this);
          $.each(itemarr,function(ind,val){
            if(jQuery.inArray(val,category_list) > -1){
              $this.fadeIn('slow');
              return false;
            }
            else
              $this.hide();
          });
        });
      }   
    });
  }); 

Upvotes: 0

Views: 151

Answers (1)

Dhananjay
Dhananjay

Reputation: 554

You need to ensure that all elements in category_list array are available in itemarr array. The post How to check whether multiple values exist within an Javascript array should solve your problem e.g in the else block, modify your code as follows:

 var item = $(this).attr('data-tag');
 var itemarr = item.split(',');
 var hideItem = false;
 for(var i = 0 , len = itemarr.length; i < len && !hideItem; i++){
     hideItem = ($.inArray(itemarr[i], category_list) == -1);
  }
  if(hideItem) {
    $this.hide();
  } else {
    $this.fadeIn('slow');
  }

Upvotes: 1

Related Questions