jQuery Autocomplete - Keywords [closed]

1

I'm using this plugin ( link ) to make a search bar on the system. It works perfectly. But I'd like to know if you can use reference words. I would search for keywords, and it would return me related elements. Example: Search for "Boat" and it shows elements with the word "Naval".

    
asked by anonymous 03.01.2017 / 14:36

1 answer

1

The source parameter supports a function ( function ), a simple example:

$(".sugestoes").autocomplete({
  source: function(request, response) {
      if (request.term === "barco") {
          response(["naval"]);
      }
  }
});
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script><scripttype="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><inputtype="text" class="sugestoes">

Using Ajax

You can combine with Ajax to return the results of a database or something else:

$(".sugestoes").autocomplete({
  source: function(request, response) {
      $.ajax("consulta.php", {
           "dataType": "json",
           "data": { "termo": request.term }
      }).done(function (resposta) {
           response(resposta);
      });
  }
});

The page can be in any language what matters is that it should return in this format:

["foo", "bar", "baz"]

To query in the backend if it is PHP use $_GET['termo'] (but you can change it to whatever you want), example:

<?php
switch ($_GET['termo'])
{
   case 'barco':
       echo '["naval", "remo", "bote"]';
   break;

   case 'foo':
       echo '["bar", "baz"]';
   break;
}
    
04.01.2017 / 16:09