Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda