Created
December 3, 2019 21:52
-
-
Save parzibyte/ae306b03d0f12da1015a059aba7e6368 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener("DOMContentLoaded", () => { | |
// El elemento que tendrá el autocompletado | |
const $inputNombre = document.querySelector("#nombre"); | |
let ac = new Awesomplete($inputNombre, { | |
list: [], // Por defecto es una lista vacía, hasta que se comienza a escribir | |
minChars: 1, // Cuántos caracteres escribir para autocompletar | |
}); | |
// Esta función filtra los datos y refresca el autocompletado | |
const refrescarLista = () => { | |
let valorDelInput = $inputNombre.value; | |
if (!valorDelInput) return; // Detener si no hay valor | |
// Buscar nombres de la base de datos con PHP | |
fetch("./nombres.php?busqueda=" + valorDelInput) | |
.then(r => r.json()) | |
.then(mascotas => { | |
// Mapeamos, ya que se requiere label y value | |
ac.list = mascotas.map(mascota => ({ | |
label: mascota.nombre, // Lo que aparece al buscar | |
value: mascota.id, // El valor que se pone en el input | |
})); | |
}); | |
}; | |
// Agregar un listener para cuando se cambie el contenido; en el mismo se refresca la lista | |
$inputNombre.addEventListener("input", () => { | |
refrescarLista(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment