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;
}
This is not what you want here: Categories?
– ShutUpMagda
I voted to leave it open, as it was possible to answer explaining the use of
API
.– Guilherme Nascimento