File size: 988 Bytes
6fc616d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// For the normal product search autocomplete
const input = document.getElementById('search-input');
const resultsBox = document.getElementById('autocomplete-results');

function showResults(results) {
  if (!results || results.length === 0) {
    resultsBox.style.display = 'none';
    return;
  }
  let html = '';
  results.forEach(item => {
    html += `<div class="autocomplete-item" onclick="goToProduct(${item.id})">${item.name}</div>`;
  });
  resultsBox.innerHTML = html;
  resultsBox.style.display = 'block';
}

function goToProduct(itemId) {
  window.location.href = '/product/' + itemId;
}

if (input && resultsBox) {
  input.addEventListener('input', function() {
    const q = this.value.trim();
    if (q.length < 1) {
      resultsBox.style.display = 'none';
      return;
    }
    fetch(`/autocomplete?q=${encodeURIComponent(q)}`)
      .then(resp => resp.json())
      .then(data => {
        showResults(data);
      })
      .catch(err => console.error(err));
  });
}