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;
}