1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- export function autocomplete (inputField, path) {
-
- const input = inputField.querySelector('input');
- input.autocomplete = 'off';
- const results = document.createElement('ul');
- results.className="autocomplete-results";
- input.addEventListener('input', (e) => {
- const term = input.value.trim();
- if (term.length === 0) {
- // Ne pas envoyer de requête si le champ est vide
- results.remove()
- return;
- }
- // Envoyer une requête Fetch
- fetch(path+ '?query=' + encodeURIComponent(term), {
- headers: {
- 'X-Requested-With': 'XMLHttpRequest'
- }
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Erreur lors de la récupération des suggestions');
- }
- return response.json();
- })
- .then(data => {
- results.innerHTML = '';
- data.forEach(element => {
- const li = document.createElement('li');
- li.innerText = element;
- li.classList.add('autocomplete-item');
- results.appendChild(li);
- li.addEventListener('click', (e) => {
- input.value = element;
- results.remove()
- })
- })
- if (data.length > 0) {
- input.after(results);
- }
- return true;
- })
- .catch(error => {
- console.error(error);
- return false;
- });
- });
- }
|