1
0
mirror of https://gitlab.crans.org/bde/nk20 synced 2024-12-28 02:12:20 +00:00
nk20/note_kfet/static/js/autocomplete_model.js

65 lines
2.3 KiB
JavaScript
Raw Normal View History

const keycodes = [32, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 106, 107, 109, 110, 111, 186, 187, 188, 189, 190, 191, 219, 220, 221, 222]
$(document).ready(function () {
2020-09-05 06:30:41 +00:00
$('.autocomplete').keyup(function (e) {
const target = $('#' + e.target.id)
const prefix = target.attr('id')
const 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' }
const input = target.val()
target.addClass('is-invalid')
target.removeClass('is-valid')
$.getJSON(api_url + (api_url.includes('?') ? '&' : '?') + 'format=json&search=^' + input + api_url_suffix, function (objects) {
2021-09-05 22:37:10 +00:00
let html = '<ul class="list-group list-group-flush" id="' + prefix + '_list">'
2020-09-05 06:30:41 +00:00
objects.results.forEach(function (obj) {
html += li(prefix + '_' + obj.id, obj[name_field])
})
2021-09-05 22:37:10 +00:00
html += '</ul>'
target.tooltip({
html: true,
placement: 'bottom',
trigger: 'manual',
container: target.parent(),
fallbackPlacement: 'clockwise'
})
2020-09-05 06:30:41 +00:00
2021-09-05 22:37:10 +00:00
target.attr("data-original-title", html).tooltip("show")
2020-09-05 06:30:41 +00:00
objects.results.forEach(function (obj) {
$('#' + prefix + '_' + obj.id).click(function () {
target.val(obj[name_field])
$('#' + prefix + '_pk').val(obj.id)
2021-09-05 22:37:10 +00:00
target.tooltip("hide")
2020-09-05 06:30:41 +00:00
target.removeClass('is-invalid')
target.addClass('is-valid')
if (typeof autocompleted !== 'undefined') { autocompleted(obj, prefix) }
})
})
if (objects.results.length >= 2) {
$('#' + prefix + '_pk').val(objects.results[0].id)
}
if (objects.results.length === 1 &&
(keycodes.includes(e.originalEvent.keyCode) ||
input === objects.results[0][name_field])) {
2021-09-05 22:37:10 +00:00
$('#' + prefix + '_' + objects.results[0].id).trigger('click')
2020-09-05 06:30:41 +00:00
}
})
})
$('.autocomplete-reset').click(function () {
const name = $(this).attr('id').replace('_reset', '')
$('#' + name + '_pk').val('')
$('#' + name).val('')
$('#' + name).tooltip('hide')
2020-09-05 06:30:41 +00:00
})
})