Dima Vleskov Dima Vleskov - 4 months ago 12
Ajax Question

how to create an exact search using Js and Jquery

I'm trying to create an expanded search where you can find people not only using there names but some combinations... for instance i have this list of players and this peace of code work fine, but if i want to find for such features like - keeper England. this line of code doesn't work ((val.position.search(myExp) != -1) || (val.nationality.search(myExp) != -1))

$("#search").keyup(function() {
var field = $("#search").val();
var myExp = new RegExp(field, "i");
$.getJSON("players.json", function(data) {
var output = "<ul>";
$.each(data, function(key, val) {
if ((val.name.search(myExp) != -1) || (val.position.search(myExp) != -1) || ((val.position.search(myExp) != -1) || (val.nationality.search(myExp) != -1))) {
output += "<li>";
output += '<p class="name">' + val.name + '</p>';
output += '<p>' + val.position + '</p>';
output += '<p>' + val.dateOfBirth + '</p>';
output += '<p>' + val.nationality + '</p>';
output += '<p>' + val.contractUntil + '</p>';
output += '<p>' + val.marketValue + '</p>';
output += "</li>";
}
});
output += "</ul>";
$("#update").html(output);
});
});

{
"id":2138,
"name":"Thibaut Courtois",
"position":"Keeper",
"jerseyNumber":13,
"dateOfBirth":"1992-05-11",
"nationality":"Belgium",
"contractUntil":"2019-06-30",
"marketValue":"35,000,000 ˆ"
},
{
"id":2140,
"name":"Jamal Blackman",
"position":"Keeper",
"jerseyNumber":27,
"dateOfBirth":"1993-10-27",
"nationality":"England",
"contractUntil":"2019-06-30",
"marketValue":"250,000 ˆ"
},

Answer

You have to do multiple search queries because you have multiple words in your query: "england keeper", "england" and "keeper"

So you want to filter the items by "england" and also by "keeper"..

The best would be to create a some more functions, each will do a part of it:

// Note: this function returns the filter function
var myFilter = function(regex) {
  return function(item) {
    return regex.test(item.name)
      || regex.test(item.position)
      || regex.test(item.nationality)
  }
}


var findMatches = function(items, searchString) {
  // make a copy of the items / data
  var found = items.slice(0, item.length);

  // split the searchString, and filter the items by it
  searchString.split(' ').forEach(function(part) {
    found = found.filter(myFilter(new RegEx(part, 'i'))
  });

  return found;
}

Now you can use it in your code:

...
var output = "<ul>";
var filteredData = findMatches(data, field);
$.each(filteredData, function(key, val) {
   // filteredData should be fine, you can just render it
}
...