2020-03-27 15:19:33 +00:00
|
|
|
$(document).ready(function () {
|
|
|
|
$(".autocomplete").keyup(function(e) {
|
|
|
|
let target = $("#" + e.target.id);
|
|
|
|
let prefix = target.attr("id");
|
|
|
|
let api_url = target.attr("api_url");
|
|
|
|
let api_url_suffix = target.attr("api_url_suffix");
|
|
|
|
if (!api_url_suffix)
|
|
|
|
api_url_suffix = "";
|
|
|
|
let name_field = target.attr("name_field");
|
|
|
|
if (!name_field)
|
|
|
|
name_field = "name";
|
|
|
|
let input = target.val();
|
|
|
|
|
2020-04-19 23:26:53 +00:00
|
|
|
$.getJSON(api_url + (api_url.includes("?") ? "&" : "?") + "format=json&search=^" + input + api_url_suffix, function(objects) {
|
2020-03-27 15:19:33 +00:00
|
|
|
let html = "";
|
|
|
|
|
|
|
|
objects.results.forEach(function (obj) {
|
|
|
|
html += li(prefix + "_" + obj.id, obj[name_field]);
|
|
|
|
});
|
|
|
|
|
2020-08-02 07:20:21 +00:00
|
|
|
let results_list = $("#" + prefix + "_list");
|
|
|
|
results_list.html(html);
|
2020-03-27 15:19:33 +00:00
|
|
|
|
|
|
|
objects.results.forEach(function (obj) {
|
|
|
|
$("#" + prefix + "_" + obj.id).click(function() {
|
|
|
|
target.val(obj[name_field]);
|
|
|
|
$("#" + prefix + "_pk").val(obj.id);
|
2020-04-05 16:37:04 +00:00
|
|
|
|
|
|
|
if (typeof autocompleted != 'undefined')
|
|
|
|
autocompleted(obj, prefix)
|
2020-03-27 15:19:33 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
if (input === obj[name_field])
|
|
|
|
$("#" + prefix + "_pk").val(obj.id);
|
|
|
|
});
|
2020-08-02 07:20:21 +00:00
|
|
|
|
|
|
|
if (results_list.children().length === 1 && e.originalEvent.keyCode >= 32) {
|
|
|
|
results_list.children().first().trigger("click");
|
|
|
|
}
|
2020-03-27 15:19:33 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|