Tengo un elemento HTML de input de tipo text . Cuando hago clic en el campo de entrada, aparece una lista de sugerencias formada por las entradas más recientes en ese campo antes de que escriba algo en el campo.
Sé que puedo bloquear toda la funcionalidad de autocompletar con autocomplete="off" pero quiero conservar la funcionalidad de autocompletar una vez que el usuario comience a escribir.
El mejor ejemplo es un formulario de inicio de sesión simple.
<body> <form> Username<input name="username" type="text"> Password<input name="password" type="password"> <button type="submit">Log In</button> </form> </body> No puedo encontrar ninguna referencia a este tipo de funcionalidad en este foro ni en ningún otro, pero según mi experiencia, la mayoría de los campos de los sitios web funcionan de esta manera. La única idea que tengo es cambiar la propiedad de autocomplete usando javascript cuando el usuario comienza a escribir, pero eso parece muy complicado. Me pregunto si hay una forma menos bruta de lograr lo que busco.
Yo uso JavaScript, y el código está debajo
También comenté todo el código si lo necesitas :)
también en HTML es mejor usar <label> porque al hacer clic en la etiqueta, se enfoca automáticamente en la entrada
ahora también agregué algunos console.log(); si quieres probar si esto funciona
// getting all the input available in the form let myInput = document.querySelectorAll("input"); // for every input I will use the function inside myInput.forEach(input => { // default, autocomplete will be disabled (because first time it will be empty) input.setAttribute("autocomplete", "off"); // I will add event listener to every input, keyup is for when the key is pressed then released. input.addEventListener("keyup", function(event) { // getting what what <input> is typing now, so we can use it in the function const ActualInput = event.target; // if the length of the input is greater than 0, then we will be ON if (ActualInput.value.length > 0) { ActualInput.setAttribute("autocomplete", "on"); console.log(ActualInput + " is ON"); // for debugging, delete later } // if the length of the input is 0, then we will be OFF and autocomplete will be disabled else { ActualInput.setAttribute("autocomplete", "off"); console.log(ActualInput + " is OFF"); // for debugging, delete later } }); }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> <script src="./script.js" defer></script> </head> <body> <form> <!-- username --> <label for="username">Username</label> <input name="username" type="text" id="username"> <!-- password --> <label for="password">Password</label> <input name="password" type="password" id="password"> <!-- submit --> <button type="submit">Log In</button> </form> </body> </html>