Vi un tutorial sobre cómo usar Javascript con Autocompletar usando un archivo JSON y Fetch. Todo funciona bien; excepto por lo siguiente:
El ejemplo en JSFiddle no funciona porque no puedo agregar ningún activo. Aquí está el código que debería borrar los datos cuando no hay caracteres en el cuadro de entrada:
if (matches.length === 0) { matchList.innerHTML = ''; // Line 31: This doesn't clear the results when no input is entered.}
Pero en el campo CSS, he codificado parte del archivo JSON para su referencia.
usando onChange() puede verificar la longitud final de la palabra clave escrita en la etiqueta de entrada, y para NULL puede simplemente ignorar la sugerencia.
Jugué con el código y lo investigué. Tuve que separar el código en dos eventos. El que faltaba era cuando se carga el DOM, luego toma una lista de estados. Aquí está el código revisado:
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));