Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda