javascriptjquerywordpressautocompletelivesearch

Live Search Filter with Multiple Words, Use AND instead of OR


I have a live search autocomplete filter that I'm using to weed out a directory of people. Using this search, I want people to be able to search using multiple words, which will further reduce the number of results they get.

Currently, with the code below, if someone searches "technician Atlanta", they will get the directoryprofile divs that contain "technician" and the ones that contain "Atlanta". What I want is for it to find a div that contains BOTH of those words...so they can find a technician that is in Atlanta. Hopefully that makes sense.

My code is working for including the terms separately, but I want them to find rows containing multiple terms. Any ideas? THANKS in advance!!

$("#filter").keyup(function () {
	// Split the current value of the filter textbox
	var data = this.value.split(" ");
	// Get the table rows
	var rows = $(".directoryprofile");
	if (this.value == "") {
	  rows.show();
	  return;
	}
			    
	// Hide all the rows initially
	rows.hide();

	// Filter the rows; check each term in data
	rows.filter(function (i, v) {
	   for (var d = 0; d < data.length; ++d) {
	       if ($(this).is(":contains('" + data[d] + "')")) {
	           return true;
	       }
	   }
	   return false;
	})
	// Show the rows that match.
	.show();
});


Solution

  • rows.filter(function(i, v) {
      var truth = true;
    
      for (var d = 0; d < data.length; ++d) {
        //remain true so long as all of the filters are found
        //if even one is not found, it will stay false
        truth = truth && $(this).is(":contains('" + data[d] + "')");
      }
    
      return truth;
    })
    
    //OR you could just flip your logic and return false if any of the
    //filters are not found
    
    rows.filter(function(i, v) {
      for (var d = 0; d < data.length; ++d) {
        if (!$(this).is(":contains('" + data[d] + "')")) {
          return false;
        }
      }
      
      return true;
    })