'Javascript Autocomplete doesn't clear suggestion with no input

I watched a tutorial on how to use Javascript with Autocomplete using a JSON file and Fetch. Everything works fine; except for the following:

  • If I clear the input, it shows all of the results in the file. I have included a comment in the code where I try to clear the results but it doesn't work.

The example on JSFiddle doesn't work because I can't add any assets. Here is the code that should be clearing the data when no characters are in the input box:

if (matches.length === 0) {
matchList.innerHTML = ''; // Line 31: This doesn't clear the results when no input is entered.

}

But in the CSS field, I have hard coded some of the JSON file for your reference.

Thanks in advance, MattThe input field is empty, it should not show any results



Solution 1:[1]

I played around with the code and researched it. I had to separate the code into two events. The one that was missing was when the DOM is loaded, then grab a list of states. Here is the revised code:

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
let states;

// Get states
const getStates = async () => {
  const res = await fetch('states.json');
  states = await res.json();
};

// FIlter states
const searchStates = (searchText) => {
  // Get matches to current text input
  let matches = states.filter((state) => {
    const regex = new RegExp(`^${searchText}`, 'gi');
    return state.name.match(regex) || state.abbr.match(regex);
  });

  // Clear when input or matches are empty
  if (searchText.length === 0) {
    matches = [];
    matchList.innerHTML = '';
  }

  outputHtml(matches);
};

// Show results in HTML
const outputHtml = (matches) => {
  if (matches.length > 0) {
    const html = matches
      .map(
        (matt) => `<div class="card card-body mb-1">
    <h4>${matt.name} (${matt.abbr}) 
    <span class="text-primary">${matt.capital}</span></h4>
    <small>Lat: ${matt.lat} / Long: ${matt.long}</small>
   </div>`
      )
      .join('');
    matchList.innerHTML = html;
  }
};

window.addEventListener('DOMContentLoaded', getStates);
search.addEventListener('input', () => searchStates(search.value));

Solution 2:[2]

using onChange() you can check final length of the keyword written in input tag, and for NULL you can just ignore the suggestion.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Musicman
Solution 2 Rohit Sonawane