autocomplete.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. export function autocomplete (inputField, path) {
  2. const input = inputField.querySelector('input');
  3. input.autocomplete = 'off';
  4. const results = document.createElement('ul');
  5. results.className="autocomplete-results";
  6. input.addEventListener('input', (e) => {
  7. const term = input.value.trim();
  8. if (term.length === 0) {
  9. // Ne pas envoyer de requête si le champ est vide
  10. results.remove()
  11. return;
  12. }
  13. // Envoyer une requête Fetch
  14. fetch(path+ '?query=' + encodeURIComponent(term), {
  15. headers: {
  16. 'X-Requested-With': 'XMLHttpRequest'
  17. }
  18. })
  19. .then(response => {
  20. if (!response.ok) {
  21. throw new Error('Erreur lors de la récupération des suggestions');
  22. }
  23. return response.json();
  24. })
  25. .then(data => {
  26. results.innerHTML = '';
  27. data.forEach(element => {
  28. const li = document.createElement('li');
  29. li.innerText = element;
  30. li.classList.add('autocomplete-item');
  31. results.appendChild(li);
  32. li.addEventListener('click', (e) => {
  33. input.value = element;
  34. results.remove()
  35. })
  36. })
  37. if (data.length > 0) {
  38. input.after(results);
  39. }
  40. return true;
  41. })
  42. .catch(error => {
  43. console.error(error);
  44. return false;
  45. });
  46. });
  47. }