jQuery Autocomplete - Keywords

Asked

Viewed 460 times

1

I’m using this plugin (https://jqueryui.com/autocomplete/) to make a search bar on the system. It works perfectly. But I would like to know if it has how to use reference words. I would like to search for keywords, and it return me related elements. Example: Search for "Boat" and it show elements with the word "Naval".

  • 1

    This is not what you want here: Categories?

  • I voted to leave it open, as it was possible to answer explaining the use of API.

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>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" class="sugestoes">

Using Ajax

You can combine with Ajax to return the results of a database or anything 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 consult in the back end if it is PHP use $_GET['termo'] (but you can change to whatever you want), example:

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

   case 'foo':
       echo '["bar", "baz"]';
   break;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.