Reputation: 102
I have an input
HTML element of type text
. When I click into the input field, a list of suggestions pops up made up of the most recent inputs to that field before I even type anything into the field.
I know that I can block all autocomplete functionality with autocomplete="off"
but I want to preserve the autocomplete functionality once the user starts typing.
The best example is a simple login form.
<body>
<form>
Username<input name="username" type="text">
Password<input name="password" type="password">
<button type="submit">Log In</button>
</form>
</body>
I can't find any references to this type of functionality on this forum or any other, but in my experience most fields on websites work this way. The one idea I have is to change the autocomplete
property using javascript when the user starts typing, but that seems very hacky. I'm wondering if there is a less brute-force way to accomplish what I'm after.
Upvotes: 0
Views: 793
Reputation: 3855
I use JavaScript, and the code is below
I also commented on all the code if you need it :)
also in HTML is best to use <label>
because on click of the label, is automatically focused on the input
now I also added some console.log();
if you want to test if this works
// 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>
Upvotes: 1