autocomplete.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. return;
  11. }
  12. // Envoyer une requête Fetch
  13. fetch(path+ '?query=' + encodeURIComponent(term), {
  14. headers: {
  15. 'X-Requested-With': 'XMLHttpRequest'
  16. }
  17. })
  18. .then(response => {
  19. if (!response.ok) {
  20. throw new Error('Erreur lors de la récupération des suggestions');
  21. }
  22. return response.json();
  23. })
  24. .then(data => {
  25. results.innerHTML = '';
  26. data.forEach(element => {
  27. const li = document.createElement('li');
  28. li.innerText = element;
  29. li.classList.add('autocomplete-item');
  30. results.appendChild(li);
  31. li.addEventListener('click', (e) => {
  32. input.value = element;
  33. results.remove()
  34. })
  35. })
  36. input.after(results);
  37. return true;
  38. })
  39. .catch(error => {
  40. console.error(error);
  41. return false;
  42. });
  43. });
  44. }